2038N/A/*
3528N/A * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
2038N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
2038N/A *
2038N/A * This code is free software; you can redistribute it and/or modify it
2038N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
2038N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
2038N/A *
2038N/A * This code is distributed in the hope that it will be useful, but WITHOUT
2038N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
2038N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
2038N/A * version 2 for more details (a copy is included in the LICENSE file that
2038N/A * accompanied this code).
2038N/A *
2038N/A * You should have received a copy of the GNU General Public License version
2038N/A * 2 along with this work; if not, write to the Free Software Foundation,
2038N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
2038N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
2038N/A */
2038N/A
2038N/A/* @test
3793N/A * @summary unit tests for java.lang.invoke.MethodHandles
5459N/A * @compile MethodHandlesTest.java remote/RemoteExample.java
3907N/A * @run junit/othervm test.java.lang.invoke.MethodHandlesTest
2038N/A */
2038N/A
3793N/Apackage test.java.lang.invoke;
2038N/A
5459N/Aimport test.java.lang.invoke.remote.RemoteExample;
3793N/Aimport java.lang.invoke.*;
3793N/Aimport java.lang.invoke.MethodHandles.Lookup;
2038N/Aimport java.lang.reflect.*;
2038N/Aimport java.util.*;
2038N/Aimport org.junit.*;
2038N/Aimport static org.junit.Assert.*;
2038N/A
2038N/A
2038N/A/**
2038N/A *
2038N/A * @author jrose
2038N/A */
2038N/Apublic class MethodHandlesTest {
5452N/A static final Class<?> THIS_CLASS = MethodHandlesTest.class;
2038N/A // How much output?
2431N/A static int verbosity = 0;
2435N/A static {
5452N/A String vstr = System.getProperty(THIS_CLASS.getSimpleName()+".verbosity");
5452N/A if (vstr == null)
5452N/A vstr = System.getProperty(THIS_CLASS.getName()+".verbosity");
2435N/A if (vstr != null) verbosity = Integer.parseInt(vstr);
2435N/A }
2038N/A
2038N/A // Set this true during development if you want to fast-forward to
2038N/A // a particular new, non-working test. Tests which are known to
2038N/A // work (or have recently worked) test this flag and return on true.
5459N/A static final boolean CAN_SKIP_WORKING;
5459N/A static {
5459N/A String vstr = System.getProperty(THIS_CLASS.getSimpleName()+".CAN_SKIP_WORKING");
5459N/A if (vstr == null)
5459N/A vstr = System.getProperty(THIS_CLASS.getName()+".CAN_SKIP_WORKING");
5459N/A CAN_SKIP_WORKING = Boolean.parseBoolean(vstr);
5459N/A }
2038N/A
5452N/A // Set 'true' to do about 15x fewer tests, especially those redundant with RicochetTest.
5452N/A // This might be useful with -Xcomp stress tests that compile all method handles.
5452N/A static boolean CAN_TEST_LIGHTLY = Boolean.getBoolean(THIS_CLASS.getName()+".CAN_TEST_LIGHTLY");
2038N/A
2038N/A @Test
2038N/A public void testFirst() throws Throwable {
2038N/A verbosity += 9; try {
2038N/A // left blank for debugging
2431N/A } finally { printCounts(); verbosity -= 9; }
2038N/A }
2038N/A
2038N/A static final int MAX_ARG_INCREASE = 3;
2038N/A
2038N/A public MethodHandlesTest() {
2038N/A }
2038N/A
2038N/A String testName;
2435N/A static int allPosTests, allNegTests;
2038N/A int posTests, negTests;
2038N/A @After
2038N/A public void printCounts() {
2431N/A if (verbosity >= 2 && (posTests | negTests) != 0) {
2038N/A System.out.println();
2038N/A if (posTests != 0) System.out.println("=== "+testName+": "+posTests+" positive test cases run");
2038N/A if (negTests != 0) System.out.println("=== "+testName+": "+negTests+" negative test cases run");
2435N/A allPosTests += posTests;
2435N/A allNegTests += negTests;
2431N/A posTests = negTests = 0;
2038N/A }
2038N/A }
2038N/A void countTest(boolean positive) {
2038N/A if (positive) ++posTests;
2038N/A else ++negTests;
2038N/A }
2038N/A void countTest() { countTest(true); }
2038N/A void startTest(String name) {
2038N/A if (testName != null) printCounts();
2431N/A if (verbosity >= 1)
2038N/A System.out.println(name);
2038N/A posTests = negTests = 0;
2038N/A testName = name;
2038N/A }
2038N/A
2038N/A @BeforeClass
2038N/A public static void setUpClass() throws Exception {
2038N/A calledLog.clear();
2038N/A calledLog.add(null);
2431N/A nextArgVal = INITIAL_ARG_VAL;
2038N/A }
2038N/A
2038N/A @AfterClass
2038N/A public static void tearDownClass() throws Exception {
2435N/A int posTests = allPosTests, negTests = allNegTests;
5452N/A if (verbosity >= 0 && (posTests | negTests) != 0) {
2435N/A System.out.println();
2435N/A if (posTests != 0) System.out.println("=== "+posTests+" total positive test cases");
2435N/A if (negTests != 0) System.out.println("=== "+negTests+" total negative test cases");
2435N/A }
2038N/A }
2038N/A
5455N/A static List<Object> calledLog = new ArrayList<>();
2038N/A static Object logEntry(String name, Object... args) {
2038N/A return Arrays.asList(name, Arrays.asList(args));
2038N/A }
5459N/A public static Object called(String name, Object... args) {
2038N/A Object entry = logEntry(name, args);
2038N/A calledLog.add(entry);
2038N/A return entry;
2038N/A }
2038N/A static void assertCalled(String name, Object... args) {
2038N/A Object expected = logEntry(name, args);
2038N/A Object actual = calledLog.get(calledLog.size() - 1);
2431N/A if (expected.equals(actual) && verbosity < 9) return;
2038N/A System.out.println("assertCalled "+name+":");
2038N/A System.out.println("expected: "+expected);
2038N/A System.out.println("actual: "+actual);
2038N/A System.out.println("ex. types: "+getClasses(expected));
2038N/A System.out.println("act. types: "+getClasses(actual));
2038N/A assertEquals("previous method call", expected, actual);
2038N/A }
2038N/A static void printCalled(MethodHandle target, String name, Object... args) {
2431N/A if (verbosity >= 3)
2431N/A System.out.println("calling MH="+target+" to "+name+Arrays.toString(args));
2038N/A }
2038N/A
2038N/A static Object castToWrapper(Object value, Class<?> dst) {
2038N/A Object wrap = null;
2038N/A if (value instanceof Number)
2038N/A wrap = castToWrapperOrNull(((Number)value).longValue(), dst);
2038N/A if (value instanceof Character)
2038N/A wrap = castToWrapperOrNull((char)(Character)value, dst);
2038N/A if (wrap != null) return wrap;
2038N/A return dst.cast(value);
2038N/A }
2038N/A
5455N/A @SuppressWarnings("cast") // primitive cast to (long) is part of the pattern
2038N/A static Object castToWrapperOrNull(long value, Class<?> dst) {
2038N/A if (dst == int.class || dst == Integer.class)
2038N/A return (int)(value);
2038N/A if (dst == long.class || dst == Long.class)
2038N/A return (long)(value);
2038N/A if (dst == char.class || dst == Character.class)
2038N/A return (char)(value);
2038N/A if (dst == short.class || dst == Short.class)
2038N/A return (short)(value);
2038N/A if (dst == float.class || dst == Float.class)
2038N/A return (float)(value);
2038N/A if (dst == double.class || dst == Double.class)
2038N/A return (double)(value);
2040N/A if (dst == byte.class || dst == Byte.class)
2040N/A return (byte)(value);
2040N/A if (dst == boolean.class || dst == boolean.class)
2040N/A return ((value % 29) & 1) == 0;
2038N/A return null;
2038N/A }
2038N/A
2431N/A static final int ONE_MILLION = (1000*1000), // first int value
2431N/A TEN_BILLION = (10*1000*1000*1000), // scale factor to reach upper 32 bits
2431N/A INITIAL_ARG_VAL = ONE_MILLION << 1; // <<1 makes space for sign bit;
2431N/A static long nextArgVal;
2431N/A static long nextArg(boolean moreBits) {
2431N/A long val = nextArgVal++;
2431N/A long sign = -(val & 1); // alternate signs
2431N/A val >>= 1;
2431N/A if (moreBits)
2431N/A // Guarantee some bits in the high word.
2431N/A // In any case keep the decimal representation simple-looking,
2431N/A // with lots of zeroes, so as not to make the printed decimal
2431N/A // strings unnecessarily noisy.
2431N/A val += (val % ONE_MILLION) * TEN_BILLION;
2431N/A return val ^ sign;
2431N/A }
2431N/A static int nextArg() {
2431N/A // Produce a 32-bit result something like ONE_MILLION+(smallint).
2431N/A // Example: 1_000_042.
2431N/A return (int) nextArg(false);
2431N/A }
2431N/A static long nextArg(Class<?> kind) {
2431N/A if (kind == long.class || kind == Long.class ||
2431N/A kind == double.class || kind == Double.class)
2431N/A // produce a 64-bit result something like
2431N/A // ((TEN_BILLION+1) * (ONE_MILLION+(smallint)))
2431N/A // Example: 10_000_420_001_000_042.
2431N/A return nextArg(true);
2431N/A return (long) nextArg();
2431N/A }
2431N/A
2038N/A static Object randomArg(Class<?> param) {
2431N/A Object wrap = castToWrapperOrNull(nextArg(param), param);
2038N/A if (wrap != null) {
2038N/A return wrap;
2038N/A }
3793N/A// import sun.invoke.util.Wrapper;
2038N/A// Wrapper wrap = Wrapper.forBasicType(dst);
2038N/A// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))
2038N/A// wrap = Wrapper.forWrapperType(dst);
2038N/A// if (wrap != Wrapper.OBJECT)
2038N/A// return wrap.wrap(nextArg++);
3012N/A if (param.isInterface()) {
3012N/A for (Class<?> c : param.getClasses()) {
3012N/A if (param.isAssignableFrom(c) && !c.isInterface())
3012N/A { param = c; break; }
3012N/A }
3012N/A }
5456N/A if (param.isInterface() && param.isAssignableFrom(List.class))
5456N/A return Arrays.asList("#"+nextArg());
2038N/A if (param.isInterface() || param.isAssignableFrom(String.class))
2431N/A return "#"+nextArg();
2038N/A else
2038N/A try {
2038N/A return param.newInstance();
5455N/A } catch (InstantiationException | IllegalAccessException ex) {
2038N/A }
2038N/A return null; // random class not Object, String, Integer, etc.
2038N/A }
2038N/A static Object[] randomArgs(Class<?>... params) {
2038N/A Object[] args = new Object[params.length];
2038N/A for (int i = 0; i < args.length; i++)
2038N/A args[i] = randomArg(params[i]);
2038N/A return args;
2038N/A }
2038N/A static Object[] randomArgs(int nargs, Class<?> param) {
2038N/A Object[] args = new Object[nargs];
2038N/A for (int i = 0; i < args.length; i++)
2038N/A args[i] = randomArg(param);
2038N/A return args;
2038N/A }
2038N/A
5455N/A @SafeVarargs @SuppressWarnings("varargs")
2038N/A static <T, E extends T> T[] array(Class<T[]> atype, E... a) {
2038N/A return Arrays.copyOf(a, a.length, atype);
2038N/A }
5455N/A @SafeVarargs @SuppressWarnings("varargs")
2038N/A static <T> T[] cat(T[] a, T... b) {
2038N/A int alen = a.length, blen = b.length;
2038N/A if (blen == 0) return a;
2038N/A T[] c = Arrays.copyOf(a, alen + blen);
2038N/A System.arraycopy(b, 0, c, alen, blen);
2038N/A return c;
2038N/A }
2038N/A static Integer[] boxAll(int... vx) {
2038N/A Integer[] res = new Integer[vx.length];
2038N/A for (int i = 0; i < res.length; i++) {
2038N/A res[i] = vx[i];
2038N/A }
2038N/A return res;
2038N/A }
2038N/A static Object getClasses(Object x) {
2038N/A if (x == null) return x;
2038N/A if (x instanceof String) return x; // keep the name
2038N/A if (x instanceof List) {
2038N/A // recursively report classes of the list elements
2038N/A Object[] xa = ((List)x).toArray();
2038N/A for (int i = 0; i < xa.length; i++)
2038N/A xa[i] = getClasses(xa[i]);
2038N/A return Arrays.asList(xa);
2038N/A }
2038N/A return x.getClass().getSimpleName();
2038N/A }
2038N/A
3529N/A /** Return lambda(arg...[arity]) { new Object[]{ arg... } } */
3529N/A static MethodHandle varargsList(int arity) {
3529N/A return ValueConversions.varargsList(arity);
3529N/A }
3529N/A /** Return lambda(arg...[arity]) { Arrays.asList(arg...) } */
3529N/A static MethodHandle varargsArray(int arity) {
3529N/A return ValueConversions.varargsArray(arity);
3529N/A }
4183N/A static MethodHandle varargsArray(Class<?> arrayType, int arity) {
4183N/A return ValueConversions.varargsArray(arrayType, arity);
4183N/A }
3529N/A /** Variation of varargsList, but with the given rtype. */
3529N/A static MethodHandle varargsList(int arity, Class<?> rtype) {
3529N/A MethodHandle list = varargsList(arity);
3529N/A MethodType listType = list.type().changeReturnType(rtype);
3529N/A if (List.class.isAssignableFrom(rtype) || rtype == void.class || rtype == Object.class) {
3529N/A // OK
3529N/A } else if (rtype.isAssignableFrom(String.class)) {
3529N/A if (LIST_TO_STRING == null)
3529N/A try {
3529N/A LIST_TO_STRING = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToString",
3529N/A MethodType.methodType(String.class, List.class));
5455N/A } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
3529N/A list = MethodHandles.filterReturnValue(list, LIST_TO_STRING);
3529N/A } else if (rtype.isPrimitive()) {
3529N/A if (LIST_TO_INT == null)
3529N/A try {
3529N/A LIST_TO_INT = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToInt",
3529N/A MethodType.methodType(int.class, List.class));
5455N/A } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
3529N/A list = MethodHandles.filterReturnValue(list, LIST_TO_INT);
3529N/A list = MethodHandles.explicitCastArguments(list, listType);
3529N/A } else {
3529N/A throw new RuntimeException("varargsList: "+rtype);
3529N/A }
3529N/A return list.asType(listType);
3529N/A }
3529N/A private static MethodHandle LIST_TO_STRING, LIST_TO_INT;
5455N/A private static String listToString(List<?> x) { return x.toString(); }
5455N/A private static int listToInt(List<?> x) { return x.toString().hashCode(); }
3529N/A
2038N/A static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
2038N/A return changeArgTypes(target, 0, 999, argType);
2038N/A }
2038N/A static MethodHandle changeArgTypes(MethodHandle target,
2038N/A int beg, int end, Class<?> argType) {
2038N/A MethodType targetType = target.type();
2038N/A end = Math.min(end, targetType.parameterCount());
5455N/A ArrayList<Class<?>> argTypes = new ArrayList<>(targetType.parameterList());
2038N/A Collections.fill(argTypes.subList(beg, end), argType);
2040N/A MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);
4250N/A return target.asType(ttype2);
2038N/A }
5452N/A static MethodHandle addTrailingArgs(MethodHandle target, int nargs, Class<?> argClass) {
5452N/A int targetLen = target.type().parameterCount();
5452N/A int extra = (nargs - targetLen);
5452N/A if (extra <= 0) return target;
5452N/A List<Class<?>> fakeArgs = Collections.<Class<?>>nCopies(extra, argClass);
5452N/A return MethodHandles.dropArguments(target, targetLen, fakeArgs);
5452N/A }
2038N/A
2038N/A // This lookup is good for all members in and under MethodHandlesTest.
2038N/A static final Lookup PRIVATE = MethodHandles.lookup();
2038N/A // This lookup is good for package-private members but not private ones.
2038N/A static final Lookup PACKAGE = PackageSibling.lookup();
5459N/A // This lookup is good for public members and protected members of PubExample
5459N/A static final Lookup SUBCLASS = RemoteExample.lookup();
2038N/A // This lookup is good only for public members.
2040N/A static final Lookup PUBLIC = MethodHandles.publicLookup();
2038N/A
2038N/A // Subject methods...
2038N/A static class Example implements IntExample {
2038N/A final String name;
2431N/A public Example() { name = "Example#"+nextArg(); }
2038N/A protected Example(String name) { this.name = name; }
5455N/A @SuppressWarnings("LeakingThisInConstructor")
2038N/A protected Example(int x) { this(); called("protected <init>", this, x); }
2038N/A @Override public String toString() { return name; }
2038N/A
2038N/A public void v0() { called("v0", this); }
5459N/A protected void pro_v0() { called("pro_v0", this); }
2038N/A void pkg_v0() { called("pkg_v0", this); }
2038N/A private void pri_v0() { called("pri_v0", this); }
2038N/A public static void s0() { called("s0"); }
5459N/A protected static void pro_s0() { called("pro_s0"); }
2038N/A static void pkg_s0() { called("pkg_s0"); }
2038N/A private static void pri_s0() { called("pri_s0"); }
2038N/A
2038N/A public Object v1(Object x) { return called("v1", this, x); }
2038N/A public Object v2(Object x, Object y) { return called("v2", this, x, y); }
2038N/A public Object v2(Object x, int y) { return called("v2", this, x, y); }
2038N/A public Object v2(int x, Object y) { return called("v2", this, x, y); }
2038N/A public Object v2(int x, int y) { return called("v2", this, x, y); }
2038N/A public static Object s1(Object x) { return called("s1", x); }
2038N/A public static Object s2(int x) { return called("s2", x); }
2038N/A public static Object s3(long x) { return called("s3", x); }
2038N/A public static Object s4(int x, int y) { return called("s4", x, y); }
2038N/A public static Object s5(long x, int y) { return called("s5", x, y); }
2038N/A public static Object s6(int x, long y) { return called("s6", x, y); }
2038N/A public static Object s7(float x, double y) { return called("s7", x, y); }
2431N/A
5452N/A // for testing findConstructor:
5452N/A public Example(String x, int y) { this.name = x+y; called("Example.<init>", x, y); }
5452N/A public Example(int x, String y) { this.name = x+y; called("Example.<init>", x, y); }
5459N/A public Example(int x, int y) { this.name = x+""+y; called("Example.<init>", x, y); }
5459N/A public Example(int x, long y) { this.name = x+""+y; called("Example.<init>", x, y); }
5459N/A public Example(int x, float y) { this.name = x+""+y; called("Example.<init>", x, y); }
5459N/A public Example(int x, double y) { this.name = x+""+y; called("Example.<init>", x, y); }
5459N/A public Example(int x, int y, int z) { this.name = x+""+y+""+z; called("Example.<init>", x, y, z); }
5459N/A public Example(int x, int y, int z, int a) { this.name = x+""+y+""+z+""+a; called("Example.<init>", x, y, z, a); }
5452N/A
2431N/A static final Lookup EXAMPLE = MethodHandles.lookup(); // for testing findSpecial
2038N/A }
2431N/A static final Lookup EXAMPLE = Example.EXAMPLE;
2038N/A public static class PubExample extends Example {
5459N/A public PubExample() { this("PubExample"); }
5459N/A protected PubExample(String prefix) { super(prefix+"#"+nextArg()); }
5459N/A protected void pro_v0() { called("Pub/pro_v0", this); }
5459N/A protected static void pro_s0() { called("Pub/pro_s0"); }
2038N/A }
2038N/A static class SubExample extends Example {
2038N/A @Override public void v0() { called("Sub/v0", this); }
2038N/A @Override void pkg_v0() { called("Sub/pkg_v0", this); }
5455N/A @SuppressWarnings("LeakingThisInConstructor")
2038N/A private SubExample(int x) { called("<init>", this, x); }
2431N/A public SubExample() { super("SubExample#"+nextArg()); }
2038N/A }
2038N/A public static interface IntExample {
2038N/A public void v0();
3012N/A public static class Impl implements IntExample {
2038N/A public void v0() { called("Int/v0", this); }
2038N/A final String name;
2431N/A public Impl() { name = "Impl#"+nextArg(); }
2431N/A @Override public String toString() { return name; }
2038N/A }
2038N/A }
5456N/A static interface SubIntExample extends IntExample { }
2038N/A
2038N/A static final Object[][][] ACCESS_CASES = {
5459N/A { { false, PUBLIC }, { false, SUBCLASS }, { false, PACKAGE }, { false, PRIVATE }, { false, EXAMPLE } }, //[0]: all false
5459N/A { { false, PUBLIC }, { false, SUBCLASS }, { false, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[1]: only PRIVATE
5459N/A { { false, PUBLIC }, { false, SUBCLASS }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[2]: PUBLIC false
5459N/A { { false, PUBLIC }, { true, SUBCLASS }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[3]: subclass OK
5459N/A { { true, PUBLIC }, { true, SUBCLASS }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[4]: all true
2038N/A };
2038N/A
2431N/A static Object[][] accessCases(Class<?> defc, String name, boolean isSpecial) {
2431N/A Object[][] cases;
2431N/A if (name.contains("pri_") || isSpecial) {
2431N/A cases = ACCESS_CASES[1]; // PRIVATE only
2431N/A } else if (name.contains("pkg_") || !Modifier.isPublic(defc.getModifiers())) {
2431N/A cases = ACCESS_CASES[2]; // not PUBLIC
5459N/A } else if (name.contains("pro_")) {
5459N/A cases = ACCESS_CASES[3]; // PUBLIC class, protected member
2040N/A } else {
5459N/A assertTrue(name.indexOf('_') < 0 || name.contains("fin_"));
2040N/A boolean pubc = Modifier.isPublic(defc.getModifiers());
2040N/A if (pubc)
5459N/A cases = ACCESS_CASES[4]; // all access levels
2431N/A else
2431N/A cases = ACCESS_CASES[2]; // PACKAGE but not PUBLIC
2040N/A }
2431N/A if (defc != Example.class && cases[cases.length-1][1] == EXAMPLE)
2431N/A cases = Arrays.copyOfRange(cases, 0, cases.length-1);
2431N/A return cases;
2431N/A }
2431N/A static Object[][] accessCases(Class<?> defc, String name) {
2431N/A return accessCases(defc, name, false);
2038N/A }
2038N/A
5459N/A static Lookup maybeMoveIn(Lookup lookup, Class<?> defc) {
5459N/A if (lookup == PUBLIC || lookup == SUBCLASS || lookup == PACKAGE)
5459N/A // external views stay external
5459N/A return lookup;
5459N/A return lookup.in(defc);
5459N/A }
5459N/A
2038N/A @Test
2038N/A public void testFindStatic() throws Throwable {
2038N/A if (CAN_SKIP_WORKING) return;
2038N/A startTest("findStatic");
2038N/A testFindStatic(PubExample.class, void.class, "s0");
2038N/A testFindStatic(Example.class, void.class, "s0");
2038N/A testFindStatic(Example.class, void.class, "pkg_s0");
2038N/A testFindStatic(Example.class, void.class, "pri_s0");
5459N/A testFindStatic(Example.class, void.class, "pro_s0");
5459N/A testFindStatic(PubExample.class, void.class, "Pub/pro_s0");
2038N/A
2038N/A testFindStatic(Example.class, Object.class, "s1", Object.class);
2038N/A testFindStatic(Example.class, Object.class, "s2", int.class);
2038N/A testFindStatic(Example.class, Object.class, "s3", long.class);
2038N/A testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
2038N/A testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
2038N/A testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
2038N/A testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
2038N/A
2038N/A testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
5459N/A testFindStatic(false, PRIVATE, Example.class, void.class, "v0");
2038N/A }
2038N/A
2038N/A void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A for (Object[] ac : accessCases(defc, name)) {
2038N/A testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
2038N/A }
2038N/A }
2038N/A void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A testFindStatic(true, lookup, defc, ret, name, params);
2038N/A }
2038N/A void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A countTest(positive);
5459N/A String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
2040N/A MethodType type = MethodType.methodType(ret, params);
2038N/A MethodHandle target = null;
3011N/A Exception noAccess = null;
2038N/A try {
2431N/A if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
5459N/A target = maybeMoveIn(lookup, defc).findStatic(defc, methodName, type);
3530N/A } catch (ReflectiveOperationException ex) {
2038N/A noAccess = ex;
5459N/A if (verbosity >= 5) ex.printStackTrace(System.out);
3530N/A if (name.contains("bogus"))
3530N/A assertTrue(noAccess instanceof NoSuchMethodException);
3530N/A else
3530N/A assertTrue(noAccess instanceof IllegalAccessException);
2038N/A }
2431N/A if (verbosity >= 3)
2431N/A System.out.println("findStatic "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
2038N/A +(noAccess == null ? "" : " !! "+noAccess));
2038N/A if (positive && noAccess != null) throw noAccess;
2038N/A assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
2038N/A if (!positive) return; // negative test failed as expected
2038N/A assertEquals(type, target.type());
5459N/A assertNameStringContains(target, methodName);
2038N/A Object[] args = randomArgs(params);
2038N/A printCalled(target, name, args);
3240N/A target.invokeWithArguments(args);
2038N/A assertCalled(name, args);
2431N/A if (verbosity >= 1)
2431N/A System.out.print(':');
2038N/A }
2038N/A
4245N/A static final boolean DEBUG_METHOD_HANDLE_NAMES = Boolean.getBoolean("java.lang.invoke.MethodHandle.DEBUG_NAMES");
4245N/A
3240N/A // rough check of name string
4245N/A static void assertNameStringContains(MethodHandle x, String s) {
4245N/A if (!DEBUG_METHOD_HANDLE_NAMES) {
4245N/A // ignore s
4245N/A assertEquals("MethodHandle"+x.type(), x.toString());
4245N/A return;
4245N/A }
3240N/A if (x.toString().contains(s)) return;
3240N/A assertEquals(s, x);
3240N/A }
3240N/A
2038N/A @Test
2038N/A public void testFindVirtual() throws Throwable {
2038N/A if (CAN_SKIP_WORKING) return;
2038N/A startTest("findVirtual");
2038N/A testFindVirtual(Example.class, void.class, "v0");
2038N/A testFindVirtual(Example.class, void.class, "pkg_v0");
2038N/A testFindVirtual(Example.class, void.class, "pri_v0");
2038N/A testFindVirtual(Example.class, Object.class, "v1", Object.class);
2038N/A testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
2038N/A testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
2038N/A testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
2038N/A testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
5459N/A testFindVirtual(Example.class, void.class, "pro_v0");
5459N/A testFindVirtual(PubExample.class, void.class, "Pub/pro_v0");
5459N/A
2038N/A testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
5459N/A testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "s0");
5459N/A
2038N/A // test dispatch
2038N/A testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
2038N/A testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
2038N/A testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
2038N/A testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
2038N/A testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
2038N/A testFindVirtual(Example.class, IntExample.class, void.class, "v0");
2038N/A testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
2038N/A }
2038N/A
2038N/A void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A Class<?> rcvc = defc;
2038N/A testFindVirtual(rcvc, defc, ret, name, params);
2038N/A }
2038N/A void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A for (Object[] ac : accessCases(defc, name)) {
2038N/A testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
2038N/A }
2038N/A }
2038N/A void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
2038N/A }
2038N/A void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A countTest(positive);
2038N/A String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
2040N/A MethodType type = MethodType.methodType(ret, params);
2038N/A MethodHandle target = null;
3011N/A Exception noAccess = null;
2038N/A try {
2431N/A if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
5459N/A target = maybeMoveIn(lookup, defc).findVirtual(defc, methodName, type);
3530N/A } catch (ReflectiveOperationException ex) {
2038N/A noAccess = ex;
5459N/A if (verbosity >= 5) ex.printStackTrace(System.out);
3530N/A if (name.contains("bogus"))
3530N/A assertTrue(noAccess instanceof NoSuchMethodException);
3530N/A else
3530N/A assertTrue(noAccess instanceof IllegalAccessException);
2038N/A }
2431N/A if (verbosity >= 3)
2431N/A System.out.println("findVirtual "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
2038N/A +(noAccess == null ? "" : " !! "+noAccess));
2038N/A if (positive && noAccess != null) throw noAccess;
2038N/A assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
2038N/A if (!positive) return; // negative test failed as expected
5459N/A Class<?> selfc = defc;
5459N/A // predict receiver type narrowing:
5459N/A if (lookup == SUBCLASS &&
5459N/A name.contains("pro_") &&
5459N/A selfc.isAssignableFrom(lookup.lookupClass())) {
5459N/A selfc = lookup.lookupClass();
5459N/A if (name.startsWith("Pub/")) name = "Rem/"+name.substring(4);
5459N/A }
5459N/A Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)selfc), params);
2040N/A MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
2431N/A assertEquals(typeWithSelf, target.type());
3240N/A assertNameStringContains(target, methodName);
2038N/A Object[] argsWithSelf = randomArgs(paramsWithSelf);
5459N/A if (selfc.isAssignableFrom(rcvc) && rcvc != selfc) argsWithSelf[0] = randomArg(rcvc);
2038N/A printCalled(target, name, argsWithSelf);
3240N/A target.invokeWithArguments(argsWithSelf);
2038N/A assertCalled(name, argsWithSelf);
2431N/A if (verbosity >= 1)
2431N/A System.out.print(':');
2038N/A }
2038N/A
2038N/A @Test
2038N/A public void testFindSpecial() throws Throwable {
2038N/A if (CAN_SKIP_WORKING) return;
2038N/A startTest("findSpecial");
2431N/A testFindSpecial(SubExample.class, Example.class, void.class, "v0");
2431N/A testFindSpecial(SubExample.class, Example.class, void.class, "pkg_v0");
5459N/A testFindSpecial(RemoteExample.class, PubExample.class, void.class, "Pub/pro_v0");
2431N/A // Do some negative testing:
3530N/A testFindSpecial(false, EXAMPLE, SubExample.class, Example.class, void.class, "bogus");
3530N/A testFindSpecial(false, PRIVATE, SubExample.class, Example.class, void.class, "bogus");
2431N/A for (Lookup lookup : new Lookup[]{ PRIVATE, EXAMPLE, PACKAGE, PUBLIC }) {
2431N/A testFindSpecial(false, lookup, Object.class, Example.class, void.class, "v0");
2431N/A testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", int.class);
2431N/A testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "s0");
2431N/A }
2038N/A }
2038N/A
2431N/A void testFindSpecial(Class<?> specialCaller,
2431N/A Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
5459N/A if (specialCaller == RemoteExample.class) {
5459N/A testFindSpecial(false, EXAMPLE, specialCaller, defc, ret, name, params);
5459N/A testFindSpecial(false, PRIVATE, specialCaller, defc, ret, name, params);
5459N/A testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
5459N/A testFindSpecial(true, SUBCLASS, specialCaller, defc, ret, name, params);
5459N/A testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
5459N/A return;
5459N/A }
5459N/A testFindSpecial(true, EXAMPLE, specialCaller, defc, ret, name, params);
5459N/A testFindSpecial(true, PRIVATE, specialCaller, defc, ret, name, params);
5459N/A testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
5459N/A testFindSpecial(false, SUBCLASS, specialCaller, defc, ret, name, params);
5459N/A testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
2038N/A }
2431N/A void testFindSpecial(boolean positive, Lookup lookup, Class<?> specialCaller,
2431N/A Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A countTest(positive);
5459N/A String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
2040N/A MethodType type = MethodType.methodType(ret, params);
2038N/A MethodHandle target = null;
3011N/A Exception noAccess = null;
2038N/A try {
2431N/A if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
5459N/A if (verbosity >= 5) System.out.println(" lookup => "+maybeMoveIn(lookup, specialCaller));
5459N/A target = maybeMoveIn(lookup, specialCaller).findSpecial(defc, methodName, type, specialCaller);
3530N/A } catch (ReflectiveOperationException ex) {
2038N/A noAccess = ex;
5459N/A if (verbosity >= 5) ex.printStackTrace(System.out);
3530N/A if (name.contains("bogus"))
3530N/A assertTrue(noAccess instanceof NoSuchMethodException);
3530N/A else
3530N/A assertTrue(noAccess instanceof IllegalAccessException);
2038N/A }
2431N/A if (verbosity >= 3)
2431N/A System.out.println("findSpecial from "+specialCaller.getName()+" to "+defc.getName()+"."+name+"/"+type+" => "+target
2431N/A +(target == null ? "" : target.type())
2431N/A +(noAccess == null ? "" : " !! "+noAccess));
2038N/A if (positive && noAccess != null) throw noAccess;
2038N/A assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
2038N/A if (!positive) return; // negative test failed as expected
2431N/A assertEquals(specialCaller, target.type().parameterType(0));
2431N/A assertEquals(type, target.type().dropParameterTypes(0,1));
2431N/A Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)specialCaller), params);
2040N/A MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
5459N/A assertNameStringContains(target, methodName);
2038N/A Object[] args = randomArgs(paramsWithSelf);
2038N/A printCalled(target, name, args);
3240N/A target.invokeWithArguments(args);
2038N/A assertCalled(name, args);
2038N/A }
2038N/A
2038N/A @Test
5452N/A public void testFindConstructor() throws Throwable {
5452N/A if (CAN_SKIP_WORKING) return;
5452N/A startTest("findConstructor");
5452N/A testFindConstructor(true, EXAMPLE, Example.class);
5452N/A testFindConstructor(true, EXAMPLE, Example.class, int.class);
5459N/A testFindConstructor(true, EXAMPLE, Example.class, int.class, int.class);
5459N/A testFindConstructor(true, EXAMPLE, Example.class, int.class, long.class);
5459N/A testFindConstructor(true, EXAMPLE, Example.class, int.class, float.class);
5459N/A testFindConstructor(true, EXAMPLE, Example.class, int.class, double.class);
5452N/A testFindConstructor(true, EXAMPLE, Example.class, String.class);
5459N/A testFindConstructor(true, EXAMPLE, Example.class, int.class, int.class, int.class);
5459N/A testFindConstructor(true, EXAMPLE, Example.class, int.class, int.class, int.class, int.class);
5452N/A }
5452N/A void testFindConstructor(boolean positive, Lookup lookup,
5452N/A Class<?> defc, Class<?>... params) throws Throwable {
5452N/A countTest(positive);
5452N/A MethodType type = MethodType.methodType(void.class, params);
5452N/A MethodHandle target = null;
5452N/A Exception noAccess = null;
5452N/A try {
5452N/A if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" <init>"+type);
5452N/A target = lookup.findConstructor(defc, type);
5452N/A } catch (ReflectiveOperationException ex) {
5452N/A noAccess = ex;
5452N/A assertTrue(noAccess instanceof IllegalAccessException);
5452N/A }
5452N/A if (verbosity >= 3)
5452N/A System.out.println("findConstructor "+defc.getName()+".<init>/"+type+" => "+target
5452N/A +(target == null ? "" : target.type())
5452N/A +(noAccess == null ? "" : " !! "+noAccess));
5452N/A if (positive && noAccess != null) throw noAccess;
5452N/A assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
5452N/A if (!positive) return; // negative test failed as expected
5452N/A assertEquals(type.changeReturnType(defc), target.type());
5452N/A Object[] args = randomArgs(params);
5452N/A printCalled(target, defc.getSimpleName(), args);
5452N/A Object obj = target.invokeWithArguments(args);
5452N/A if (!(defc == Example.class && params.length < 2))
5452N/A assertCalled(defc.getSimpleName()+".<init>", args);
5452N/A assertTrue("instance of "+defc.getName(), defc.isInstance(obj));
5452N/A }
5452N/A
5452N/A @Test
2038N/A public void testBind() throws Throwable {
2038N/A if (CAN_SKIP_WORKING) return;
2038N/A startTest("bind");
2038N/A testBind(Example.class, void.class, "v0");
2038N/A testBind(Example.class, void.class, "pkg_v0");
2038N/A testBind(Example.class, void.class, "pri_v0");
2038N/A testBind(Example.class, Object.class, "v1", Object.class);
2038N/A testBind(Example.class, Object.class, "v2", Object.class, Object.class);
2038N/A testBind(Example.class, Object.class, "v2", Object.class, int.class);
2038N/A testBind(Example.class, Object.class, "v2", int.class, Object.class);
2038N/A testBind(Example.class, Object.class, "v2", int.class, int.class);
2038N/A testBind(false, PRIVATE, Example.class, void.class, "bogus");
2038N/A testBind(SubExample.class, void.class, "Sub/v0");
2038N/A testBind(SubExample.class, void.class, "Sub/pkg_v0");
2038N/A testBind(IntExample.Impl.class, void.class, "Int/v0");
2038N/A }
2038N/A
2038N/A void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A for (Object[] ac : accessCases(defc, name)) {
2038N/A testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
2038N/A }
2038N/A }
2038N/A
2038N/A void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A countTest(positive);
2038N/A String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
2040N/A MethodType type = MethodType.methodType(ret, params);
2038N/A Object receiver = randomArg(defc);
2038N/A MethodHandle target = null;
3011N/A Exception noAccess = null;
2038N/A try {
2431N/A if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
5459N/A target = maybeMoveIn(lookup, defc).bind(receiver, methodName, type);
3530N/A } catch (ReflectiveOperationException ex) {
2038N/A noAccess = ex;
5459N/A if (verbosity >= 5) ex.printStackTrace(System.out);
3530N/A if (name.contains("bogus"))
3530N/A assertTrue(noAccess instanceof NoSuchMethodException);
3530N/A else
3530N/A assertTrue(noAccess instanceof IllegalAccessException);
2038N/A }
2431N/A if (verbosity >= 3)
2038N/A System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
2038N/A +(noAccess == null ? "" : " !! "+noAccess));
2038N/A if (positive && noAccess != null) throw noAccess;
2038N/A assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
2038N/A if (!positive) return; // negative test failed as expected
2038N/A assertEquals(type, target.type());
2038N/A Object[] args = randomArgs(params);
2038N/A printCalled(target, name, args);
3240N/A target.invokeWithArguments(args);
2038N/A Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
2038N/A assertCalled(name, argsWithReceiver);
2431N/A if (verbosity >= 1)
2431N/A System.out.print(':');
2038N/A }
2038N/A
2038N/A @Test
2038N/A public void testUnreflect() throws Throwable {
2038N/A if (CAN_SKIP_WORKING) return;
2038N/A startTest("unreflect");
2038N/A testUnreflect(Example.class, true, void.class, "s0");
5459N/A testUnreflect(Example.class, true, void.class, "pro_s0");
2038N/A testUnreflect(Example.class, true, void.class, "pkg_s0");
2038N/A testUnreflect(Example.class, true, void.class, "pri_s0");
2038N/A
2038N/A testUnreflect(Example.class, true, Object.class, "s1", Object.class);
2038N/A testUnreflect(Example.class, true, Object.class, "s2", int.class);
2431N/A testUnreflect(Example.class, true, Object.class, "s3", long.class);
2431N/A testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
2431N/A testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
2431N/A testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
2038N/A
2038N/A testUnreflect(Example.class, false, void.class, "v0");
2038N/A testUnreflect(Example.class, false, void.class, "pkg_v0");
2038N/A testUnreflect(Example.class, false, void.class, "pri_v0");
2038N/A testUnreflect(Example.class, false, Object.class, "v1", Object.class);
2038N/A testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
2038N/A testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
2038N/A testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
2038N/A testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
5459N/A
5459N/A // Test a public final member in another package:
5459N/A testUnreflect(RemoteExample.class, false, void.class, "Rem/fin_v0");
2038N/A }
2038N/A
2038N/A void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A for (Object[] ac : accessCases(defc, name)) {
2431N/A testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, (isStatic ? null : defc), ret, name, params);
2038N/A }
2038N/A }
2431N/A void testUnreflect(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2431N/A for (Object[] ac : accessCases(defc, name)) {
2431N/A testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
2431N/A }
2431N/A }
2431N/A void testUnreflectMaybeSpecial(Class<?> specialCaller,
2431N/A boolean positive, Lookup lookup,
2431N/A Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2038N/A countTest(positive);
5459N/A String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
2040N/A MethodType type = MethodType.methodType(ret, params);
5459N/A Method rmethod = defc.getDeclaredMethod(methodName, params);
2038N/A MethodHandle target = null;
3011N/A Exception noAccess = null;
2431N/A boolean isStatic = (rcvc == null);
2431N/A boolean isSpecial = (specialCaller != null);
2038N/A try {
2431N/A if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
2431N/A if (isSpecial)
5459N/A target = maybeMoveIn(lookup, specialCaller).unreflectSpecial(rmethod, specialCaller);
2431N/A else
5459N/A target = maybeMoveIn(lookup, defc).unreflect(rmethod);
3530N/A } catch (ReflectiveOperationException ex) {
2038N/A noAccess = ex;
5459N/A if (verbosity >= 5) ex.printStackTrace(System.out);
3530N/A if (name.contains("bogus"))
3530N/A assertTrue(noAccess instanceof NoSuchMethodException);
3530N/A else
3530N/A assertTrue(noAccess instanceof IllegalAccessException);
2038N/A }
2431N/A if (verbosity >= 3)
2431N/A System.out.println("unreflect"+(isSpecial?"Special":"")+" "+defc.getName()+"."+name+"/"+type
2431N/A +(!isSpecial ? "" : " specialCaller="+specialCaller)
2431N/A +( isStatic ? "" : " receiver="+rcvc)
2431N/A +" => "+target
2431N/A +(noAccess == null ? "" : " !! "+noAccess));
2038N/A if (positive && noAccess != null) throw noAccess;
2038N/A assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
2038N/A if (!positive) return; // negative test failed as expected
2431N/A assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
2038N/A Class<?>[] paramsMaybeWithSelf = params;
2038N/A if (!isStatic) {
2431N/A paramsMaybeWithSelf = cat(array(Class[].class, (Class)rcvc), params);
2038N/A }
2040N/A MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
2431N/A if (isStatic) {
2431N/A assertEquals(typeMaybeWithSelf, target.type());
2431N/A } else {
2431N/A if (isSpecial)
2431N/A assertEquals(specialCaller, target.type().parameterType(0));
2431N/A else
2431N/A assertEquals(defc, target.type().parameterType(0));
2431N/A assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
2431N/A }
2038N/A Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
2038N/A printCalled(target, name, argsMaybeWithSelf);
3240N/A target.invokeWithArguments(argsMaybeWithSelf);
2038N/A assertCalled(name, argsMaybeWithSelf);
2431N/A if (verbosity >= 1)
2431N/A System.out.print(':');
2431N/A }
2431N/A
2431N/A void testUnreflectSpecial(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
2431N/A for (Object[] ac : accessCases(defc, name, true)) {
2431N/A Class<?> specialCaller = rcvc;
2431N/A testUnreflectMaybeSpecial(specialCaller, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
2431N/A }
2038N/A }
2038N/A
2431N/A @Test
2038N/A public void testUnreflectSpecial() throws Throwable {
2431N/A if (CAN_SKIP_WORKING) return;
2038N/A startTest("unreflectSpecial");
2431N/A testUnreflectSpecial(Example.class, Example.class, void.class, "v0");
2431N/A testUnreflectSpecial(Example.class, SubExample.class, void.class, "v0");
2431N/A testUnreflectSpecial(Example.class, Example.class, void.class, "pkg_v0");
2431N/A testUnreflectSpecial(Example.class, SubExample.class, void.class, "pkg_v0");
2431N/A testUnreflectSpecial(Example.class, Example.class, Object.class, "v2", int.class, int.class);
2431N/A testUnreflectSpecial(Example.class, SubExample.class, Object.class, "v2", int.class, int.class);
2431N/A testUnreflectMaybeSpecial(Example.class, false, PRIVATE, Example.class, Example.class, void.class, "s0");
2038N/A }
2038N/A
2040N/A public static class HasFields {
2040N/A boolean fZ = false;
2040N/A byte fB = (byte)'B';
2040N/A short fS = (short)'S';
2040N/A char fC = 'C';
2040N/A int fI = 'I';
2040N/A long fJ = 'J';
2040N/A float fF = 'F';
2040N/A double fD = 'D';
2040N/A static boolean sZ = true;
2040N/A static byte sB = 1+(byte)'B';
2040N/A static short sS = 1+(short)'S';
2040N/A static char sC = 1+'C';
2040N/A static int sI = 1+'I';
2040N/A static long sJ = 1+'J';
2040N/A static float sF = 1+'F';
2040N/A static double sD = 1+'D';
2040N/A
2040N/A Object fL = 'L';
2040N/A String fR = "R";
2040N/A static Object sL = 'M';
2040N/A static String sR = "S";
2040N/A
2040N/A static final Object[][] CASES;
2040N/A static {
5455N/A ArrayList<Object[]> cases = new ArrayList<>();
2040N/A Object types[][] = {
2040N/A {'L',Object.class}, {'R',String.class},
2040N/A {'I',int.class}, {'J',long.class},
2040N/A {'F',float.class}, {'D',double.class},
2040N/A {'Z',boolean.class}, {'B',byte.class},
2040N/A {'S',short.class}, {'C',char.class},
2040N/A };
2040N/A HasFields fields = new HasFields();
2040N/A for (Object[] t : types) {
2040N/A for (int kind = 0; kind <= 1; kind++) {
2040N/A boolean isStatic = (kind != 0);
2040N/A char btc = (Character)t[0];
2040N/A String name = (isStatic ? "s" : "f") + btc;
2040N/A Class<?> type = (Class<?>) t[1];
2040N/A Object value;
2040N/A Field field;
4183N/A try {
2040N/A field = HasFields.class.getDeclaredField(name);
5455N/A } catch (NoSuchFieldException | SecurityException ex) {
2040N/A throw new InternalError("no field HasFields."+name);
2040N/A }
2040N/A try {
2040N/A value = field.get(fields);
5455N/A } catch (IllegalArgumentException | IllegalAccessException ex) {
2040N/A throw new InternalError("cannot fetch field HasFields."+name);
2040N/A }
2040N/A if (type == float.class) {
2040N/A float v = 'F';
2040N/A if (isStatic) v++;
3530N/A assertTrue(value.equals(v));
2040N/A }
3530N/A assertTrue(name.equals(field.getName()));
3530N/A assertTrue(type.equals(field.getType()));
3530N/A assertTrue(isStatic == (Modifier.isStatic(field.getModifiers())));
2040N/A cases.add(new Object[]{ field, value });
2040N/A }
2040N/A }
3530N/A cases.add(new Object[]{ new Object[]{ false, HasFields.class, "bogus_fD", double.class }, Error.class });
3530N/A cases.add(new Object[]{ new Object[]{ true, HasFields.class, "bogus_sL", Object.class }, Error.class });
2040N/A CASES = cases.toArray(new Object[0][]);
2040N/A }
2040N/A }
2040N/A
5459N/A static final int TEST_UNREFLECT = 1, TEST_FIND_FIELD = 2, TEST_FIND_STATIC = 3, TEST_SETTER = 0x10, TEST_BOUND = 0x20, TEST_NPE = 0x40;
2435N/A static boolean testModeMatches(int testMode, boolean isStatic) {
2435N/A switch (testMode) {
3530N/A case TEST_FIND_STATIC: return isStatic;
2435N/A case TEST_FIND_FIELD: return !isStatic;
3530N/A case TEST_UNREFLECT: return true; // unreflect matches both
2435N/A }
3530N/A throw new InternalError("testMode="+testMode);
2435N/A }
2435N/A
2040N/A @Test
2038N/A public void testUnreflectGetter() throws Throwable {
5459N/A if (CAN_SKIP_WORKING) return;
2435N/A startTest("unreflectGetter");
2435N/A testGetter(TEST_UNREFLECT);
2435N/A }
2435N/A @Test
2435N/A public void testFindGetter() throws Throwable {
5459N/A if (CAN_SKIP_WORKING) return;
2435N/A startTest("findGetter");
2435N/A testGetter(TEST_FIND_FIELD);
5459N/A testGetter(TEST_FIND_FIELD | TEST_BOUND);
2435N/A }
2435N/A @Test
2435N/A public void testFindStaticGetter() throws Throwable {
5459N/A if (CAN_SKIP_WORKING) return;
2435N/A startTest("findStaticGetter");
3530N/A testGetter(TEST_FIND_STATIC);
2435N/A }
2435N/A public void testGetter(int testMode) throws Throwable {
2038N/A Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
2040N/A for (Object[] c : HasFields.CASES) {
3530N/A boolean positive = (c[1] != Error.class);
3530N/A testGetter(positive, lookup, c[0], c[1], testMode);
5456N/A if (positive)
5456N/A testGetter(positive, lookup, c[0], c[1], testMode | TEST_NPE);
3530N/A }
3530N/A testGetter(true, lookup,
3530N/A new Object[]{ true, System.class, "out", java.io.PrintStream.class },
3530N/A System.out, testMode);
3530N/A for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
3530N/A testGetter(false, lookup,
3530N/A new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
3530N/A null, testMode);
2040N/A }
2040N/A }
3530N/A public void testGetter(boolean positive, MethodHandles.Lookup lookup,
3530N/A Object fieldRef, Object value, int testMode) throws Throwable {
3530N/A testAccessor(positive, lookup, fieldRef, value, testMode);
3530N/A }
3530N/A
5456N/A public void testAccessor(boolean positive0, MethodHandles.Lookup lookup,
3530N/A Object fieldRef, Object value, int testMode0) throws Throwable {
5452N/A if (verbosity >= 4)
5456N/A System.out.println("testAccessor"+Arrays.deepToString(new Object[]{positive0, lookup, fieldRef, value, testMode0}));
3530N/A boolean isGetter = ((testMode0 & TEST_SETTER) == 0);
5459N/A boolean doBound = ((testMode0 & TEST_BOUND) != 0);
5456N/A boolean testNPE = ((testMode0 & TEST_NPE) != 0);
5459N/A int testMode = testMode0 & ~(TEST_SETTER | TEST_BOUND | TEST_NPE);
5456N/A boolean positive = positive0 && !testNPE;
3530N/A boolean isStatic;
3530N/A Class<?> fclass;
3530N/A String fname;
3530N/A Class<?> ftype;
3530N/A Field f = (fieldRef instanceof Field ? (Field)fieldRef : null);
3530N/A if (f != null) {
3530N/A isStatic = Modifier.isStatic(f.getModifiers());
3530N/A fclass = f.getDeclaringClass();
3530N/A fname = f.getName();
3530N/A ftype = f.getType();
3530N/A } else {
3530N/A Object[] scnt = (Object[]) fieldRef;
3530N/A isStatic = (Boolean) scnt[0];
3530N/A fclass = (Class<?>) scnt[1];
3530N/A fname = (String) scnt[2];
3530N/A ftype = (Class<?>) scnt[3];
3530N/A try {
3530N/A f = fclass.getDeclaredField(fname);
3530N/A } catch (ReflectiveOperationException ex) {
3530N/A f = null;
3530N/A }
3530N/A }
2435N/A if (!testModeMatches(testMode, isStatic)) return;
3530N/A if (f == null && testMode == TEST_UNREFLECT) return;
5456N/A if (testNPE && isStatic) return;
3530N/A countTest(positive);
3530N/A MethodType expType;
3530N/A if (isGetter)
3530N/A expType = MethodType.methodType(ftype, HasFields.class);
3530N/A else
3530N/A expType = MethodType.methodType(void.class, HasFields.class, ftype);
2040N/A if (isStatic) expType = expType.dropParameterTypes(0, 1);
3530N/A Exception noAccess = null;
3530N/A MethodHandle mh;
3530N/A try {
5459N/A switch (testMode0 & ~(TEST_BOUND | TEST_NPE)) {
3530N/A case TEST_UNREFLECT: mh = lookup.unreflectGetter(f); break;
3530N/A case TEST_FIND_FIELD: mh = lookup.findGetter(fclass, fname, ftype); break;
3530N/A case TEST_FIND_STATIC: mh = lookup.findStaticGetter(fclass, fname, ftype); break;
3530N/A case TEST_SETTER|
3530N/A TEST_UNREFLECT: mh = lookup.unreflectSetter(f); break;
3530N/A case TEST_SETTER|
3530N/A TEST_FIND_FIELD: mh = lookup.findSetter(fclass, fname, ftype); break;
3530N/A case TEST_SETTER|
3530N/A TEST_FIND_STATIC: mh = lookup.findStaticSetter(fclass, fname, ftype); break;
3530N/A default:
3530N/A throw new InternalError("testMode="+testMode);
3530N/A }
3530N/A } catch (ReflectiveOperationException ex) {
3530N/A mh = null;
3530N/A noAccess = ex;
5459N/A if (verbosity >= 5) ex.printStackTrace(System.out);
3530N/A if (fname.contains("bogus"))
3530N/A assertTrue(noAccess instanceof NoSuchFieldException);
3530N/A else
3530N/A assertTrue(noAccess instanceof IllegalAccessException);
3530N/A }
3530N/A if (verbosity >= 3)
3530N/A System.out.println("find"+(isStatic?"Static":"")+(isGetter?"Getter":"Setter")+" "+fclass.getName()+"."+fname+"/"+ftype
3530N/A +" => "+mh
3530N/A +(noAccess == null ? "" : " !! "+noAccess));
5456N/A if (positive && !testNPE && noAccess != null) throw new RuntimeException(noAccess);
5456N/A assertEquals(positive0 ? "positive test" : "negative test erroneously passed", positive0, mh != null);
5456N/A if (!positive && !testNPE) return; // negative access test failed as expected
3530N/A assertEquals((isStatic ? 0 : 1)+(isGetter ? 0 : 1), mh.type().parameterCount());
3530N/A
3530N/A
2040N/A assertSame(mh.type(), expType);
5459N/A //assertNameStringContains(mh, fname); // This does not hold anymore with LFs
2040N/A HasFields fields = new HasFields();
5456N/A HasFields fieldsForMH = fields;
5456N/A if (testNPE) fieldsForMH = null; // perturb MH argument to elicit expected error
5459N/A if (doBound)
5459N/A mh = mh.bindTo(fieldsForMH);
2040N/A Object sawValue;
3530N/A Class<?> vtype = ftype;
3530N/A if (ftype != int.class) vtype = Object.class;
3530N/A if (isGetter) {
4250N/A mh = mh.asType(mh.type().generic()
4250N/A .changeReturnType(vtype));
3530N/A } else {
3530N/A int last = mh.type().parameterCount() - 1;
4250N/A mh = mh.asType(mh.type().generic()
4250N/A .changeReturnType(void.class)
4250N/A .changeParameterType(last, vtype));
3530N/A }
3530N/A if (f != null && f.getDeclaringClass() == HasFields.class) {
3530N/A assertEquals(f.get(fields), value); // clean to start with
3530N/A }
5456N/A Throwable caughtEx = null;
3530N/A if (isGetter) {
3530N/A Object expValue = value;
3530N/A for (int i = 0; i <= 1; i++) {
5459N/A sawValue = null; // make DA rules happy under try/catch
5459N/A try {
5459N/A if (isStatic || doBound) {
5459N/A if (ftype == int.class)
5459N/A sawValue = (int) mh.invokeExact(); // do these exactly
5459N/A else
5459N/A sawValue = mh.invokeExact();
5459N/A } else {
5456N/A if (ftype == int.class)
5456N/A sawValue = (int) mh.invokeExact((Object) fieldsForMH);
5456N/A else
5456N/A sawValue = mh.invokeExact((Object) fieldsForMH);
5459N/A }
5459N/A } catch (RuntimeException ex) {
5459N/A if (ex instanceof NullPointerException && testNPE) {
5459N/A caughtEx = ex;
5459N/A break;
5456N/A }
3530N/A }
3530N/A assertEquals(sawValue, expValue);
3530N/A if (f != null && f.getDeclaringClass() == HasFields.class
3530N/A && !Modifier.isFinal(f.getModifiers())) {
3530N/A Object random = randomArg(ftype);
3530N/A f.set(fields, random);
3530N/A expValue = random;
3530N/A } else {
3530N/A break;
3530N/A }
2040N/A }
3530N/A } else {
3530N/A for (int i = 0; i <= 1; i++) {
3530N/A Object putValue = randomArg(ftype);
5459N/A try {
5459N/A if (isStatic || doBound) {
5459N/A if (ftype == int.class)
5459N/A mh.invokeExact((int)putValue); // do these exactly
5459N/A else
5459N/A mh.invokeExact(putValue);
5459N/A } else {
5456N/A if (ftype == int.class)
5456N/A mh.invokeExact((Object) fieldsForMH, (int)putValue);
5456N/A else
5456N/A mh.invokeExact((Object) fieldsForMH, putValue);
5459N/A }
5459N/A } catch (RuntimeException ex) {
5459N/A if (ex instanceof NullPointerException && testNPE) {
5459N/A caughtEx = ex;
5459N/A break;
5456N/A }
3530N/A }
3530N/A if (f != null && f.getDeclaringClass() == HasFields.class) {
3530N/A assertEquals(f.get(fields), putValue);
3530N/A }
3530N/A }
2040N/A }
3530N/A if (f != null && f.getDeclaringClass() == HasFields.class) {
3530N/A f.set(fields, value); // put it back
3530N/A }
5456N/A if (testNPE) {
5456N/A if (caughtEx == null || !(caughtEx instanceof NullPointerException))
5456N/A throw new RuntimeException("failed to catch NPE exception"+(caughtEx == null ? " (caughtEx=null)" : ""), caughtEx);
5456N/A caughtEx = null; // nullify expected exception
5456N/A }
5456N/A if (caughtEx != null) {
5456N/A throw new RuntimeException("unexpected exception", caughtEx);
5456N/A }
2038N/A }
2038N/A
2040N/A
2040N/A @Test
2038N/A public void testUnreflectSetter() throws Throwable {
5459N/A if (CAN_SKIP_WORKING) return;
2435N/A startTest("unreflectSetter");
2435N/A testSetter(TEST_UNREFLECT);
2435N/A }
2435N/A @Test
2435N/A public void testFindSetter() throws Throwable {
5459N/A if (CAN_SKIP_WORKING) return;
2435N/A startTest("findSetter");
2435N/A testSetter(TEST_FIND_FIELD);
5459N/A testSetter(TEST_FIND_FIELD | TEST_BOUND);
2435N/A }
2435N/A @Test
2435N/A public void testFindStaticSetter() throws Throwable {
5459N/A if (CAN_SKIP_WORKING) return;
2435N/A startTest("findStaticSetter");
3530N/A testSetter(TEST_FIND_STATIC);
2435N/A }
2435N/A public void testSetter(int testMode) throws Throwable {
2038N/A Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
2038N/A startTest("unreflectSetter");
2040N/A for (Object[] c : HasFields.CASES) {
3530N/A boolean positive = (c[1] != Error.class);
3530N/A testSetter(positive, lookup, c[0], c[1], testMode);
5456N/A if (positive)
5456N/A testSetter(positive, lookup, c[0], c[1], testMode | TEST_NPE);
3530N/A }
3530N/A for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
3530N/A testSetter(false, lookup,
3530N/A new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
3530N/A null, testMode);
2040N/A }
2040N/A }
3530N/A public void testSetter(boolean positive, MethodHandles.Lookup lookup,
3530N/A Object fieldRef, Object value, int testMode) throws Throwable {
3530N/A testAccessor(positive, lookup, fieldRef, value, testMode | TEST_SETTER);
2038N/A }
2038N/A
2040N/A @Test
2038N/A public void testArrayElementGetter() throws Throwable {
5459N/A if (CAN_SKIP_WORKING) return;
2038N/A startTest("arrayElementGetter");
2431N/A testArrayElementGetterSetter(false);
2040N/A }
2040N/A
2040N/A @Test
2040N/A public void testArrayElementSetter() throws Throwable {
5459N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("arrayElementSetter");
2431N/A testArrayElementGetterSetter(true);
2431N/A }
2431N/A
5456N/A private static final int TEST_ARRAY_NONE = 0, TEST_ARRAY_NPE = 1, TEST_ARRAY_OOB = 2, TEST_ARRAY_ASE = 3;
5456N/A
2431N/A public void testArrayElementGetterSetter(boolean testSetter) throws Throwable {
5456N/A testArrayElementGetterSetter(testSetter, TEST_ARRAY_NONE);
5456N/A }
5456N/A
5456N/A @Test
5456N/A public void testArrayElementErrors() throws Throwable {
5459N/A if (CAN_SKIP_WORKING) return;
5456N/A startTest("arrayElementErrors");
5456N/A testArrayElementGetterSetter(false, TEST_ARRAY_NPE);
5456N/A testArrayElementGetterSetter(true, TEST_ARRAY_NPE);
5456N/A testArrayElementGetterSetter(false, TEST_ARRAY_OOB);
5456N/A testArrayElementGetterSetter(true, TEST_ARRAY_OOB);
5456N/A testArrayElementGetterSetter(new Object[10], true, TEST_ARRAY_ASE);
5456N/A testArrayElementGetterSetter(new Example[10], true, TEST_ARRAY_ASE);
5456N/A testArrayElementGetterSetter(new IntExample[10], true, TEST_ARRAY_ASE);
2038N/A }
2038N/A
5456N/A public void testArrayElementGetterSetter(boolean testSetter, int negTest) throws Throwable {
5456N/A testArrayElementGetterSetter(new String[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new Iterable<?>[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new Example[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new IntExample[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new Object[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new boolean[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new byte[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new char[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new short[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new int[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new float[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new long[10], testSetter, negTest);
5456N/A testArrayElementGetterSetter(new double[10], testSetter, negTest);
5456N/A }
5456N/A
5456N/A public void testArrayElementGetterSetter(Object array, boolean testSetter, int negTest) throws Throwable {
5456N/A boolean positive = (negTest == TEST_ARRAY_NONE);
5456N/A int length = java.lang.reflect.Array.getLength(array);
2040N/A Class<?> arrayType = array.getClass();
2040N/A Class<?> elemType = arrayType.getComponentType();
5456N/A Object arrayToMH = array;
5456N/A // this stanza allows negative tests to make argument perturbations:
5456N/A switch (negTest) {
5456N/A case TEST_ARRAY_NPE:
5456N/A arrayToMH = null;
5456N/A break;
5456N/A case TEST_ARRAY_OOB:
5456N/A assert(length > 0);
5456N/A arrayToMH = java.lang.reflect.Array.newInstance(elemType, 0);
5456N/A break;
5456N/A case TEST_ARRAY_ASE:
5456N/A assert(testSetter && !elemType.isPrimitive());
5456N/A if (elemType == Object.class)
5456N/A arrayToMH = new StringBuffer[length]; // very random subclass of Object!
5456N/A else if (elemType == Example.class)
5456N/A arrayToMH = new SubExample[length];
5456N/A else if (elemType == IntExample.class)
5456N/A arrayToMH = new SubIntExample[length];
5456N/A else
5456N/A return; // can't make an ArrayStoreException test
5456N/A assert(arrayType.isInstance(arrayToMH))
5456N/A : Arrays.asList(arrayType, arrayToMH.getClass(), testSetter, negTest);
5456N/A break;
5456N/A }
5456N/A countTest(positive);
5456N/A if (verbosity > 2) System.out.println("array type = "+array.getClass().getComponentType().getName()+"["+length+"]"+(positive ? "" : " negative test #"+negTest+" using "+Arrays.deepToString(new Object[]{arrayToMH})));
2040N/A MethodType expType = !testSetter
2040N/A ? MethodType.methodType(elemType, arrayType, int.class)
2040N/A : MethodType.methodType(void.class, arrayType, int.class, elemType);
2040N/A MethodHandle mh = !testSetter
2040N/A ? MethodHandles.arrayElementGetter(arrayType)
2040N/A : MethodHandles.arrayElementSetter(arrayType);
2040N/A assertSame(mh.type(), expType);
2431N/A if (elemType != int.class && elemType != boolean.class) {
5456N/A MethodType gtype = mh.type().generic().changeParameterType(1, int.class);
4183N/A if (testSetter) gtype = gtype.changeReturnType(void.class);
4250N/A mh = mh.asType(gtype);
2431N/A }
2040N/A Object sawValue, expValue;
2040N/A List<Object> model = array2list(array);
5456N/A Throwable caughtEx = null;
2040N/A for (int i = 0; i < length; i++) {
2040N/A // update array element
2040N/A Object random = randomArg(elemType);
2040N/A model.set(i, random);
2040N/A if (testSetter) {
5456N/A try {
5456N/A if (elemType == int.class)
5456N/A mh.invokeExact((int[]) arrayToMH, i, (int)random);
5456N/A else if (elemType == boolean.class)
5456N/A mh.invokeExact((boolean[]) arrayToMH, i, (boolean)random);
5456N/A else
5456N/A mh.invokeExact(arrayToMH, i, random);
5456N/A } catch (RuntimeException ex) {
5456N/A caughtEx = ex;
5456N/A break;
5456N/A }
2040N/A assertEquals(model, array2list(array));
2040N/A } else {
2040N/A Array.set(array, i, random);
2431N/A }
2431N/A if (verbosity >= 5) {
2431N/A List<Object> array2list = array2list(array);
2431N/A System.out.println("a["+i+"]="+random+" => "+array2list);
2431N/A if (!array2list.equals(model))
2431N/A System.out.println("*** != "+model);
2040N/A }
2040N/A // observe array element
2040N/A sawValue = Array.get(array, i);
2040N/A if (!testSetter) {
2040N/A expValue = sawValue;
5456N/A try {
5456N/A if (elemType == int.class)
5456N/A sawValue = (int) mh.invokeExact((int[]) arrayToMH, i);
5456N/A else if (elemType == boolean.class)
5456N/A sawValue = (boolean) mh.invokeExact((boolean[]) arrayToMH, i);
5456N/A else
5456N/A sawValue = mh.invokeExact(arrayToMH, i);
5456N/A } catch (RuntimeException ex) {
5456N/A caughtEx = ex;
5456N/A break;
5456N/A }
2040N/A assertEquals(sawValue, expValue);
2040N/A assertEquals(model, array2list(array));
2040N/A }
2040N/A }
5456N/A if (!positive) {
5456N/A if (caughtEx == null)
5456N/A throw new RuntimeException("failed to catch exception for negTest="+negTest);
5456N/A // test the kind of exception
5456N/A Class<?> reqType = null;
5456N/A switch (negTest) {
5456N/A case TEST_ARRAY_ASE: reqType = ArrayStoreException.class; break;
5456N/A case TEST_ARRAY_OOB: reqType = ArrayIndexOutOfBoundsException.class; break;
5456N/A case TEST_ARRAY_NPE: reqType = NullPointerException.class; break;
5456N/A default: assert(false);
5456N/A }
5456N/A if (reqType.isInstance(caughtEx)) {
5456N/A caughtEx = null; // nullify expected exception
5456N/A }
5456N/A }
5456N/A if (caughtEx != null) {
5456N/A throw new RuntimeException("unexpected exception", caughtEx);
5456N/A }
2040N/A }
2040N/A
2040N/A List<Object> array2list(Object array) {
2040N/A int length = Array.getLength(array);
5455N/A ArrayList<Object> model = new ArrayList<>(length);
2040N/A for (int i = 0; i < length; i++)
2040N/A model.add(Array.get(array, i));
2040N/A return model;
2038N/A }
2038N/A
2038N/A static class Callee {
2038N/A static Object id() { return called("id"); }
2038N/A static Object id(Object x) { return called("id", x); }
2038N/A static Object id(Object x, Object y) { return called("id", x, y); }
2038N/A static Object id(Object x, Object y, Object z) { return called("id", x, y, z); }
2038N/A static Object id(Object... vx) { return called("id", vx); }
2038N/A static MethodHandle ofType(int n) {
2038N/A return ofType(Object.class, n);
2038N/A }
2038N/A static MethodHandle ofType(Class<?> rtype, int n) {
2038N/A if (n == -1)
2040N/A return ofType(MethodType.methodType(rtype, Object[].class));
2040N/A return ofType(MethodType.genericMethodType(n).changeReturnType(rtype));
2038N/A }
2038N/A static MethodHandle ofType(Class<?> rtype, Class<?>... ptypes) {
2040N/A return ofType(MethodType.methodType(rtype, ptypes));
2038N/A }
2038N/A static MethodHandle ofType(MethodType type) {
2038N/A Class<?> rtype = type.returnType();
2038N/A String pfx = "";
2038N/A if (rtype != Object.class)
2038N/A pfx = rtype.getSimpleName().substring(0, 1).toLowerCase();
2038N/A String name = pfx+"id";
3011N/A try {
3011N/A return PRIVATE.findStatic(Callee.class, name, type);
5455N/A } catch (NoSuchMethodException | IllegalAccessException ex) {
3011N/A throw new RuntimeException(ex);
3011N/A }
2038N/A }
2038N/A }
2038N/A
2038N/A @Test
2038N/A public void testConvertArguments() throws Throwable {
2038N/A if (CAN_SKIP_WORKING) return;
2038N/A startTest("convertArguments");
2038N/A testConvert(Callee.ofType(1), null, "id", int.class);
2038N/A testConvert(Callee.ofType(1), null, "id", String.class);
2038N/A testConvert(Callee.ofType(1), null, "id", Integer.class);
2038N/A testConvert(Callee.ofType(1), null, "id", short.class);
2431N/A testConvert(Callee.ofType(1), null, "id", char.class);
2431N/A testConvert(Callee.ofType(1), null, "id", byte.class);
2038N/A }
2038N/A
2038N/A void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
4250N/A testConvert(true, id, rtype, name, params);
2038N/A }
2038N/A
4250N/A void testConvert(boolean positive,
3240N/A MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
2038N/A countTest(positive);
2038N/A MethodType idType = id.type();
2038N/A if (rtype == null) rtype = idType.returnType();
2038N/A for (int i = 0; i < params.length; i++) {
2038N/A if (params[i] == null) params[i] = idType.parameterType(i);
2038N/A }
2038N/A // simulate the pairwise conversion
2040N/A MethodType newType = MethodType.methodType(rtype, params);
2038N/A Object[] args = randomArgs(newType.parameterArray());
2038N/A Object[] convArgs = args.clone();
2038N/A for (int i = 0; i < args.length; i++) {
2038N/A Class<?> src = newType.parameterType(i);
2038N/A Class<?> dst = idType.parameterType(i);
2038N/A if (src != dst)
2038N/A convArgs[i] = castToWrapper(convArgs[i], dst);
2038N/A }
3240N/A Object convResult = id.invokeWithArguments(convArgs);
2038N/A {
2038N/A Class<?> dst = newType.returnType();
2038N/A Class<?> src = idType.returnType();
2038N/A if (src != dst)
2038N/A convResult = castToWrapper(convResult, dst);
2038N/A }
2038N/A MethodHandle target = null;
2038N/A RuntimeException error = null;
2038N/A try {
4250N/A target = id.asType(newType);
5462N/A } catch (WrongMethodTypeException ex) {
2038N/A error = ex;
2038N/A }
2431N/A if (verbosity >= 3)
2038N/A System.out.println("convert "+id+ " to "+newType+" => "+target
2038N/A +(error == null ? "" : " !! "+error));
2038N/A if (positive && error != null) throw error;
2038N/A assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
2038N/A if (!positive) return; // negative test failed as expected
2038N/A assertEquals(newType, target.type());
2038N/A printCalled(target, id.toString(), args);
3240N/A Object result = target.invokeWithArguments(args);
2038N/A assertCalled(name, convArgs);
2038N/A assertEquals(convResult, result);
2431N/A if (verbosity >= 1)
2431N/A System.out.print(':');
2038N/A }
2038N/A
2038N/A @Test
3528N/A public void testVarargsCollector() throws Throwable {
5459N/A if (CAN_SKIP_WORKING) return;
5459N/A startTest("varargsCollector");
3528N/A MethodHandle vac0 = PRIVATE.findStatic(MethodHandlesTest.class, "called",
3528N/A MethodType.methodType(Object.class, String.class, Object[].class));
3528N/A vac0 = vac0.bindTo("vac");
3528N/A MethodHandle vac = vac0.asVarargsCollector(Object[].class);
4250N/A testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
4250N/A testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
5455N/A for (Class<?> at : new Class<?>[] { Object.class, String.class, Integer.class }) {
4250N/A testConvert(true, vac.asType(MethodType.genericMethodType(1)), null, "vac", at);
4250N/A testConvert(true, vac.asType(MethodType.genericMethodType(2)), null, "vac", at, at);
3528N/A }
3528N/A }
3528N/A
5459N/A @Test // SLOW
2040N/A public void testPermuteArguments() throws Throwable {
2040N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("permuteArguments");
5452N/A testPermuteArguments(4, Integer.class, 2, long.class, 6);
5452N/A if (CAN_TEST_LIGHTLY) return;
2040N/A testPermuteArguments(4, Integer.class, 2, String.class, 0);
4250N/A testPermuteArguments(6, Integer.class, 0, null, 30);
2040N/A }
2040N/A public void testPermuteArguments(int max, Class<?> type1, int t2c, Class<?> type2, int dilution) throws Throwable {
2431N/A if (verbosity >= 2)
2040N/A System.out.println("permuteArguments "+max+"*"+type1.getName()
2040N/A +(t2c==0?"":"/"+t2c+"*"+type2.getName())
2040N/A +(dilution > 0 ? " with dilution "+dilution : ""));
2040N/A int t2pos = t2c == 0 ? 0 : 1;
2040N/A for (int inargs = t2pos+1; inargs <= max; inargs++) {
2040N/A Class<?>[] types = new Class<?>[inargs];
2040N/A Arrays.fill(types, type1);
2040N/A if (t2c != 0) {
2040N/A // Fill in a middle range with type2:
2040N/A Arrays.fill(types, t2pos, Math.min(t2pos+t2c, inargs), type2);
2040N/A }
2040N/A Object[] args = randomArgs(types);
2040N/A int numcases = 1;
2040N/A for (int outargs = 0; outargs <= max; outargs++) {
2040N/A if (outargs - inargs >= MAX_ARG_INCREASE) continue;
2040N/A int casStep = dilution + 1;
2040N/A // Avoid some common factors:
2040N/A while ((casStep > 2 && casStep % 2 == 0 && inargs % 2 == 0) ||
2040N/A (casStep > 3 && casStep % 3 == 0 && inargs % 3 == 0))
2040N/A casStep++;
4183N/A testPermuteArguments(args, types, outargs, numcases, casStep);
2040N/A numcases *= inargs;
5452N/A if (CAN_TEST_LIGHTLY && outargs < max-2) continue;
2040N/A if (dilution > 10 && outargs >= 4) {
5452N/A if (CAN_TEST_LIGHTLY) continue;
4183N/A int[] reorder = new int[outargs];
2040N/A // Do some special patterns, which we probably missed.
2040N/A // Replication of a single argument or argument pair.
2040N/A for (int i = 0; i < inargs; i++) {
2040N/A Arrays.fill(reorder, i);
2040N/A testPermuteArguments(args, types, reorder);
2040N/A for (int d = 1; d <= 2; d++) {
2040N/A if (i + d >= inargs) continue;
2040N/A for (int j = 1; j < outargs; j += 2)
2040N/A reorder[j] += 1;
2040N/A testPermuteArguments(args, types, reorder);
2040N/A testPermuteArguments(args, types, reverse(reorder));
2040N/A }
2040N/A }
2040N/A // Repetition of a sequence of 3 or more arguments.
2040N/A for (int i = 1; i < inargs; i++) {
2040N/A for (int len = 3; len <= inargs; len++) {
2040N/A for (int j = 0; j < outargs; j++)
2040N/A reorder[j] = (i + (j % len)) % inargs;
2040N/A testPermuteArguments(args, types, reorder);
2040N/A testPermuteArguments(args, types, reverse(reorder));
2040N/A }
2040N/A }
2040N/A }
2040N/A }
2040N/A }
2040N/A }
2040N/A
4183N/A public void testPermuteArguments(Object[] args, Class<?>[] types,
4183N/A int outargs, int numcases, int casStep) throws Throwable {
4183N/A int inargs = args.length;
4183N/A int[] reorder = new int[outargs];
4183N/A for (int cas = 0; cas < numcases; cas += casStep) {
4183N/A for (int i = 0, c = cas; i < outargs; i++) {
4183N/A reorder[i] = c % inargs;
4183N/A c /= inargs;
4183N/A }
5452N/A if (CAN_TEST_LIGHTLY && outargs >= 3 && (reorder[0] == reorder[1] || reorder[1] == reorder[2])) continue;
4183N/A testPermuteArguments(args, types, reorder);
4183N/A }
4183N/A }
4183N/A
2040N/A static int[] reverse(int[] reorder) {
2040N/A reorder = reorder.clone();
2040N/A for (int i = 0, imax = reorder.length / 2; i < imax; i++) {
2040N/A int j = reorder.length - 1 - i;
2040N/A int tem = reorder[i];
2040N/A reorder[i] = reorder[j];
2040N/A reorder[j] = tem;
2040N/A }
2040N/A return reorder;
2040N/A }
2040N/A
2040N/A void testPermuteArguments(Object[] args, Class<?>[] types, int[] reorder) throws Throwable {
2040N/A countTest();
2040N/A if (args == null && types == null) {
2040N/A int max = 0;
2040N/A for (int j : reorder) {
2040N/A if (max < j) max = j;
2040N/A }
2040N/A args = randomArgs(max+1, Integer.class);
2040N/A }
2040N/A if (args == null) {
2040N/A args = randomArgs(types);
2040N/A }
2040N/A if (types == null) {
2040N/A types = new Class<?>[args.length];
2040N/A for (int i = 0; i < args.length; i++)
2040N/A types[i] = args[i].getClass();
2040N/A }
2040N/A int inargs = args.length, outargs = reorder.length;
3530N/A assertTrue(inargs == types.length);
2431N/A if (verbosity >= 3)
2040N/A System.out.println("permuteArguments "+Arrays.toString(reorder));
2040N/A Object[] permArgs = new Object[outargs];
2040N/A Class<?>[] permTypes = new Class<?>[outargs];
2040N/A for (int i = 0; i < outargs; i++) {
2040N/A permArgs[i] = args[reorder[i]];
2040N/A permTypes[i] = types[reorder[i]];
2040N/A }
2431N/A if (verbosity >= 4) {
2040N/A System.out.println("in args: "+Arrays.asList(args));
2040N/A System.out.println("out args: "+Arrays.asList(permArgs));
2040N/A System.out.println("in types: "+Arrays.asList(types));
2040N/A System.out.println("out types: "+Arrays.asList(permTypes));
2040N/A }
2040N/A MethodType inType = MethodType.methodType(Object.class, types);
2040N/A MethodType outType = MethodType.methodType(Object.class, permTypes);
4250N/A MethodHandle target = varargsList(outargs).asType(outType);
2040N/A MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
4250N/A if (verbosity >= 5) System.out.println("newTarget = "+newTarget);
3240N/A Object result = newTarget.invokeWithArguments(args);
2040N/A Object expected = Arrays.asList(permArgs);
4183N/A if (!expected.equals(result)) {
4183N/A System.out.println("*** failed permuteArguments "+Arrays.toString(reorder)+" types="+Arrays.asList(types));
4183N/A System.out.println("in args: "+Arrays.asList(args));
4183N/A System.out.println("out args: "+expected);
4183N/A System.out.println("bad args: "+result);
4183N/A }
2040N/A assertEquals(expected, result);
2040N/A }
2040N/A
2040N/A
5459N/A @Test // SLOW
2040N/A public void testSpreadArguments() throws Throwable {
2040N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("spreadArguments");
5455N/A for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
2431N/A if (verbosity >= 3)
2040N/A System.out.println("spreadArguments "+argType);
5452N/A for (int nargs = 0; nargs < 50; nargs++) {
5459N/A if (CAN_TEST_LIGHTLY && nargs > 11) break;
5452N/A for (int pos = 0; pos <= nargs; pos++) {
5452N/A if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
5452N/A if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
5452N/A continue;
5452N/A testSpreadArguments(argType, pos, nargs);
2040N/A }
2040N/A }
2040N/A }
2040N/A }
2040N/A public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
2040N/A countTest();
4183N/A Class<?> arrayType = java.lang.reflect.Array.newInstance(argType, 0).getClass();
4183N/A MethodHandle target2 = varargsArray(arrayType, nargs);
4183N/A MethodHandle target = target2.asType(target2.type().generic());
2431N/A if (verbosity >= 3)
2040N/A System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
2040N/A Object[] args = randomArgs(target2.type().parameterArray());
2040N/A // make sure the target does what we think it does:
4183N/A if (pos == 0 && nargs < 5 && !argType.isPrimitive()) {
5455N/A Object[] check = (Object[]) target.invokeWithArguments(args);
2040N/A assertArrayEquals(args, check);
2040N/A switch (nargs) {
2040N/A case 0:
4183N/A check = (Object[]) (Object) target.invokeExact();
2040N/A assertArrayEquals(args, check);
2040N/A break;
2040N/A case 1:
4183N/A check = (Object[]) (Object) target.invokeExact(args[0]);
2040N/A assertArrayEquals(args, check);
2040N/A break;
2040N/A case 2:
4183N/A check = (Object[]) (Object) target.invokeExact(args[0], args[1]);
2040N/A assertArrayEquals(args, check);
2040N/A break;
2040N/A }
2040N/A }
5455N/A List<Class<?>> newParams = new ArrayList<>(target2.type().parameterList());
2040N/A { // modify newParams in place
2040N/A List<Class<?>> spreadParams = newParams.subList(pos, nargs);
4183N/A spreadParams.clear(); spreadParams.add(arrayType);
2040N/A }
4183N/A MethodType newType = MethodType.methodType(arrayType, newParams);
4183N/A MethodHandle result = target2.asSpreader(arrayType, nargs-pos);
4183N/A assert(result.type() == newType) : Arrays.asList(result, newType);
4183N/A result = result.asType(newType.generic());
4183N/A Object returnValue;
2040N/A if (pos == 0) {
4183N/A Object args2 = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
4183N/A returnValue = result.invokeExact(args2);
2040N/A } else {
2040N/A Object[] args1 = Arrays.copyOfRange(args, 0, pos+1);
4183N/A args1[pos] = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
4183N/A returnValue = result.invokeWithArguments(args1);
2040N/A }
4183N/A String argstr = Arrays.toString(args);
4183N/A if (!argType.isPrimitive()) {
4183N/A Object[] rv = (Object[]) returnValue;
4183N/A String rvs = Arrays.toString(rv);
4183N/A if (!Arrays.equals(args, rv)) {
4183N/A System.out.println("method: "+result);
4183N/A System.out.println("expected: "+argstr);
4183N/A System.out.println("returned: "+rvs);
4183N/A assertArrayEquals(args, rv);
4183N/A }
4183N/A } else if (argType == int.class) {
4183N/A String rvs = Arrays.toString((int[]) returnValue);
4183N/A if (!argstr.equals(rvs)) {
4183N/A System.out.println("method: "+result);
4183N/A System.out.println("expected: "+argstr);
4183N/A System.out.println("returned: "+rvs);
4183N/A assertEquals(argstr, rvs);
4183N/A }
4183N/A } else if (argType == long.class) {
4183N/A String rvs = Arrays.toString((long[]) returnValue);
4183N/A if (!argstr.equals(rvs)) {
4183N/A System.out.println("method: "+result);
4183N/A System.out.println("expected: "+argstr);
4183N/A System.out.println("returned: "+rvs);
4183N/A assertEquals(argstr, rvs);
4183N/A }
4183N/A } else {
4183N/A // cannot test...
4183N/A }
2040N/A }
2040N/A
5459N/A @Test // SLOW
2040N/A public void testCollectArguments() throws Throwable {
2040N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("collectArguments");
5455N/A for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
2431N/A if (verbosity >= 3)
2040N/A System.out.println("collectArguments "+argType);
5452N/A for (int nargs = 0; nargs < 50; nargs++) {
5459N/A if (CAN_TEST_LIGHTLY && nargs > 11) break;
5452N/A for (int pos = 0; pos <= nargs; pos++) {
5452N/A if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
5452N/A if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
5452N/A continue;
2040N/A testCollectArguments(argType, pos, nargs);
2040N/A }
2040N/A }
2040N/A }
2040N/A }
2040N/A public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
2040N/A countTest();
2040N/A // fake up a MH with the same type as the desired adapter:
3529N/A MethodHandle fake = varargsArray(nargs);
2040N/A fake = changeArgTypes(fake, argType);
2040N/A MethodType newType = fake.type();
2040N/A Object[] args = randomArgs(newType.parameterArray());
2040N/A // here is what should happen:
2040N/A Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
2040N/A collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
2040N/A // here is the MH which will witness the collected argument tail:
3529N/A MethodHandle target = varargsArray(pos+1);
2040N/A target = changeArgTypes(target, 0, pos, argType);
2040N/A target = changeArgTypes(target, pos, pos+1, Object[].class);
2431N/A if (verbosity >= 3)
2040N/A System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
3529N/A MethodHandle result = target.asCollector(Object[].class, nargs-pos).asType(newType);
3240N/A Object[] returnValue = (Object[]) result.invokeWithArguments(args);
2040N/A// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
2040N/A// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
2040N/A// collectedArgs[pos] = Arrays.asList((Object[]) collectedArgs[pos]);
2040N/A assertArrayEquals(collectedArgs, returnValue);
2040N/A }
2040N/A
5459N/A @Test // SLOW
2038N/A public void testInsertArguments() throws Throwable {
2038N/A if (CAN_SKIP_WORKING) return;
2038N/A startTest("insertArguments");
5452N/A for (int nargs = 0; nargs < 50; nargs++) {
5459N/A if (CAN_TEST_LIGHTLY && nargs > 11) break;
5452N/A for (int ins = 0; ins <= nargs; ins++) {
5452N/A if (nargs > 10 && ins > 4 && ins < nargs-4 && ins % 10 != 3)
5452N/A continue;
2038N/A for (int pos = 0; pos <= nargs; pos++) {
5452N/A if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
5452N/A continue;
5452N/A if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
2038N/A testInsertArguments(nargs, pos, ins);
2038N/A }
2038N/A }
2038N/A }
2038N/A }
2038N/A
2038N/A void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
2038N/A countTest();
3529N/A MethodHandle target = varargsArray(nargs + ins);
2038N/A Object[] args = randomArgs(target.type().parameterArray());
2038N/A List<Object> resList = Arrays.asList(args);
5455N/A List<Object> argsToPass = new ArrayList<>(resList);
2038N/A List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
2431N/A if (verbosity >= 3)
5459N/A System.out.println("insert: "+argsToInsert+" @"+pos+" into "+target);
5455N/A @SuppressWarnings("cast") // cast to spread Object... is helpful
2040N/A MethodHandle target2 = MethodHandles.insertArguments(target, pos,
5455N/A (Object[]/*...*/) argsToInsert.toArray());
2038N/A argsToInsert.clear(); // remove from argsToInsert
3240N/A Object res2 = target2.invokeWithArguments(argsToPass);
2038N/A Object res2List = Arrays.asList((Object[])res2);
2431N/A if (verbosity >= 3)
2038N/A System.out.println("result: "+res2List);
2038N/A //if (!resList.equals(res2List))
2038N/A // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
2038N/A assertEquals(resList, res2List);
2038N/A }
2038N/A
2040N/A @Test
3529N/A public void testFilterReturnValue() throws Throwable {
3529N/A if (CAN_SKIP_WORKING) return;
3529N/A startTest("filterReturnValue");
3529N/A Class<?> classOfVCList = varargsList(1).invokeWithArguments(0).getClass();
3529N/A assertTrue(List.class.isAssignableFrom(classOfVCList));
3529N/A for (int nargs = 0; nargs <= 3; nargs++) {
5455N/A for (Class<?> rtype : new Class<?>[] { Object.class,
3529N/A List.class,
3529N/A int.class,
5452N/A byte.class,
5452N/A long.class,
3529N/A CharSequence.class,
3529N/A String.class }) {
3529N/A testFilterReturnValue(nargs, rtype);
3529N/A }
3529N/A }
3529N/A }
3529N/A
3529N/A void testFilterReturnValue(int nargs, Class<?> rtype) throws Throwable {
3529N/A countTest();
3529N/A MethodHandle target = varargsList(nargs, rtype);
3529N/A MethodHandle filter;
3529N/A if (List.class.isAssignableFrom(rtype) || rtype.isAssignableFrom(List.class))
3529N/A filter = varargsList(1); // add another layer of list-ness
3529N/A else
3529N/A filter = MethodHandles.identity(rtype);
3529N/A filter = filter.asType(MethodType.methodType(target.type().returnType(), rtype));
3529N/A Object[] argsToPass = randomArgs(nargs, Object.class);
3529N/A if (verbosity >= 3)
3529N/A System.out.println("filter "+target+" to "+rtype.getSimpleName()+" with "+filter);
3529N/A MethodHandle target2 = MethodHandles.filterReturnValue(target, filter);
3529N/A if (verbosity >= 4)
3529N/A System.out.println("filtered target: "+target2);
3529N/A // Simulate expected effect of filter on return value:
3529N/A Object unfiltered = target.invokeWithArguments(argsToPass);
3529N/A Object expected = filter.invokeWithArguments(unfiltered);
3529N/A if (verbosity >= 4)
3529N/A System.out.println("unfiltered: "+unfiltered+" : "+unfiltered.getClass().getSimpleName());
3529N/A if (verbosity >= 4)
3529N/A System.out.println("expected: "+expected+" : "+expected.getClass().getSimpleName());
3529N/A Object result = target2.invokeWithArguments(argsToPass);
3529N/A if (verbosity >= 3)
3529N/A System.out.println("result: "+result+" : "+result.getClass().getSimpleName());
3529N/A if (!expected.equals(result))
3529N/A System.out.println("*** fail at n/rt = "+nargs+"/"+rtype.getSimpleName()+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
3529N/A assertEquals(expected, result);
3529N/A }
3529N/A
3529N/A @Test
2040N/A public void testFilterArguments() throws Throwable {
2040N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("filterArguments");
2040N/A for (int nargs = 1; nargs <= 6; nargs++) {
2040N/A for (int pos = 0; pos < nargs; pos++) {
2040N/A testFilterArguments(nargs, pos);
2040N/A }
2040N/A }
2040N/A }
2040N/A
2040N/A void testFilterArguments(int nargs, int pos) throws Throwable {
2040N/A countTest();
3529N/A MethodHandle target = varargsList(nargs);
3529N/A MethodHandle filter = varargsList(1);
4250N/A filter = filter.asType(filter.type().generic());
2040N/A Object[] argsToPass = randomArgs(nargs, Object.class);
2431N/A if (verbosity >= 3)
2040N/A System.out.println("filter "+target+" at "+pos+" with "+filter);
3240N/A MethodHandle target2 = MethodHandles.filterArguments(target, pos, filter);
2040N/A // Simulate expected effect of filter on arglist:
2040N/A Object[] filteredArgs = argsToPass.clone();
2431N/A filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
2040N/A List<Object> expected = Arrays.asList(filteredArgs);
3240N/A Object result = target2.invokeWithArguments(argsToPass);
2431N/A if (verbosity >= 3)
2040N/A System.out.println("result: "+result);
2040N/A if (!expected.equals(result))
3529N/A System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
2040N/A assertEquals(expected, result);
2040N/A }
2040N/A
2040N/A @Test
2040N/A public void testFoldArguments() throws Throwable {
2040N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("foldArguments");
2040N/A for (int nargs = 0; nargs <= 4; nargs++) {
2040N/A for (int fold = 0; fold <= nargs; fold++) {
2040N/A for (int pos = 0; pos <= nargs; pos++) {
2040N/A testFoldArguments(nargs, pos, fold);
2040N/A }
2040N/A }
2040N/A }
2040N/A }
2040N/A
2040N/A void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
2040N/A if (pos != 0) return; // can fold only at pos=0 for now
2040N/A countTest();
3529N/A MethodHandle target = varargsList(1 + nargs);
3529N/A MethodHandle combine = varargsList(fold).asType(MethodType.genericMethodType(fold));
2040N/A List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
2431N/A if (verbosity >= 3)
2040N/A System.out.println("fold "+target+" with "+combine);
2040N/A MethodHandle target2 = MethodHandles.foldArguments(target, combine);
2040N/A // Simulate expected effect of combiner on arglist:
5455N/A List<Object> expected = new ArrayList<>(argsToPass);
2040N/A List<Object> argsToFold = expected.subList(pos, pos + fold);
2431N/A if (verbosity >= 3)
2040N/A System.out.println("fold: "+argsToFold+" into "+target2);
3240N/A Object foldedArgs = combine.invokeWithArguments(argsToFold);
2040N/A argsToFold.add(0, foldedArgs);
3240N/A Object result = target2.invokeWithArguments(argsToPass);
2431N/A if (verbosity >= 3)
2040N/A System.out.println("result: "+result);
2040N/A if (!expected.equals(result))
3529N/A System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result+" != "+expected);
2040N/A assertEquals(expected, result);
2040N/A }
2040N/A
2040N/A @Test
2040N/A public void testDropArguments() throws Throwable {
2040N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("dropArguments");
2040N/A for (int nargs = 0; nargs <= 4; nargs++) {
2040N/A for (int drop = 1; drop <= 4; drop++) {
2040N/A for (int pos = 0; pos <= nargs; pos++) {
2040N/A testDropArguments(nargs, pos, drop);
2040N/A }
2040N/A }
2040N/A }
2040N/A }
2040N/A
2040N/A void testDropArguments(int nargs, int pos, int drop) throws Throwable {
2040N/A countTest();
3529N/A MethodHandle target = varargsArray(nargs);
2040N/A Object[] args = randomArgs(target.type().parameterArray());
2040N/A MethodHandle target2 = MethodHandles.dropArguments(target, pos,
5455N/A Collections.nCopies(drop, Object.class).toArray(new Class<?>[0]));
2040N/A List<Object> resList = Arrays.asList(args);
5455N/A List<Object> argsToDrop = new ArrayList<>(resList);
2040N/A for (int i = drop; i > 0; i--) {
2040N/A argsToDrop.add(pos, "blort#"+i);
2040N/A }
3240N/A Object res2 = target2.invokeWithArguments(argsToDrop);
2040N/A Object res2List = Arrays.asList((Object[])res2);
2040N/A //if (!resList.equals(res2List))
2040N/A // System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
2040N/A assertEquals(resList, res2List);
2040N/A }
2040N/A
5459N/A @Test // SLOW
2040N/A public void testInvokers() throws Throwable {
2040N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("exactInvoker, genericInvoker, varargsInvoker, dynamicInvoker");
2040N/A // exactInvoker, genericInvoker, varargsInvoker[0..N], dynamicInvoker
5455N/A Set<MethodType> done = new HashSet<>();
2040N/A for (int i = 0; i <= 6; i++) {
5452N/A if (CAN_TEST_LIGHTLY && i > 3) break;
2040N/A MethodType gtype = MethodType.genericMethodType(i);
5455N/A for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
2040N/A for (int j = -1; j < i; j++) {
2040N/A MethodType type = gtype;
2040N/A if (j < 0)
2040N/A type = type.changeReturnType(argType);
2040N/A else if (argType == void.class)
2040N/A continue;
2040N/A else
2040N/A type = type.changeParameterType(j, argType);
2040N/A if (done.add(type))
2040N/A testInvokers(type);
2040N/A MethodType vtype = type.changeReturnType(void.class);
2040N/A if (done.add(vtype))
2040N/A testInvokers(vtype);
2040N/A }
2040N/A }
2040N/A }
2040N/A }
2040N/A
2040N/A public void testInvokers(MethodType type) throws Throwable {
2431N/A if (verbosity >= 3)
2040N/A System.out.println("test invokers for "+type);
2040N/A int nargs = type.parameterCount();
2040N/A boolean testRetCode = type.returnType() != void.class;
2040N/A MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
2040N/A MethodType.genericMethodType(0, true));
3529N/A assertTrue(target.isVarargsCollector());
3529N/A target = target.asType(type);
2040N/A Object[] args = randomArgs(type.parameterArray());
5455N/A List<Object> targetPlusArgs = new ArrayList<>(Arrays.asList(args));
2040N/A targetPlusArgs.add(0, target);
2040N/A int code = (Integer) invokee(args);
2040N/A Object log = logEntry("invokee", args);
2040N/A assertEquals(log.hashCode(), code);
2040N/A assertCalled("invokee", args);
2040N/A MethodHandle inv;
2040N/A Object result;
2040N/A // exact invoker
2040N/A countTest();
2040N/A calledLog.clear();
2040N/A inv = MethodHandles.exactInvoker(type);
3240N/A result = inv.invokeWithArguments(targetPlusArgs);
2040N/A if (testRetCode) assertEquals(code, result);
2040N/A assertCalled("invokee", args);
2040N/A // generic invoker
2040N/A countTest();
4182N/A inv = MethodHandles.invoker(type);
4250N/A if (nargs <= 3 && type == type.generic()) {
2040N/A calledLog.clear();
2040N/A switch (nargs) {
2040N/A case 0:
2431N/A result = inv.invokeExact(target);
2040N/A break;
2040N/A case 1:
2431N/A result = inv.invokeExact(target, args[0]);
2040N/A break;
2040N/A case 2:
2431N/A result = inv.invokeExact(target, args[0], args[1]);
2040N/A break;
2040N/A case 3:
2431N/A result = inv.invokeExact(target, args[0], args[1], args[2]);
2040N/A break;
2040N/A }
2040N/A if (testRetCode) assertEquals(code, result);
2040N/A assertCalled("invokee", args);
2040N/A }
2040N/A calledLog.clear();
3240N/A result = inv.invokeWithArguments(targetPlusArgs);
2040N/A if (testRetCode) assertEquals(code, result);
2040N/A assertCalled("invokee", args);
2040N/A // varargs invoker #0
2040N/A calledLog.clear();
3528N/A inv = MethodHandles.spreadInvoker(type, 0);
4250N/A if (type.returnType() == Object.class) {
4250N/A result = inv.invokeExact(target, args);
4250N/A } else if (type.returnType() == void.class) {
4250N/A result = null; inv.invokeExact(target, args);
4250N/A } else {
4250N/A result = inv.invokeWithArguments(target, (Object) args);
4250N/A }
2040N/A if (testRetCode) assertEquals(code, result);
2040N/A assertCalled("invokee", args);
4250N/A if (nargs >= 1 && type == type.generic()) {
2040N/A // varargs invoker #1
2040N/A calledLog.clear();
3528N/A inv = MethodHandles.spreadInvoker(type, 1);
2431N/A result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
2040N/A if (testRetCode) assertEquals(code, result);
2040N/A assertCalled("invokee", args);
2040N/A }
4250N/A if (nargs >= 2 && type == type.generic()) {
2040N/A // varargs invoker #2
2040N/A calledLog.clear();
3528N/A inv = MethodHandles.spreadInvoker(type, 2);
2431N/A result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
2040N/A if (testRetCode) assertEquals(code, result);
2040N/A assertCalled("invokee", args);
2040N/A }
4250N/A if (nargs >= 3 && type == type.generic()) {
2040N/A // varargs invoker #3
2040N/A calledLog.clear();
3528N/A inv = MethodHandles.spreadInvoker(type, 3);
2431N/A result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
2040N/A if (testRetCode) assertEquals(code, result);
2040N/A assertCalled("invokee", args);
2040N/A }
2040N/A for (int k = 0; k <= nargs; k++) {
2040N/A // varargs invoker #0..N
5452N/A if (CAN_TEST_LIGHTLY && (k > 1 || k < nargs - 1)) continue;
2040N/A countTest();
2040N/A calledLog.clear();
3528N/A inv = MethodHandles.spreadInvoker(type, k);
4250N/A MethodType expType = (type.dropParameterTypes(k, nargs)
4250N/A .appendParameterTypes(Object[].class)
4250N/A .insertParameterTypes(0, MethodHandle.class));
4250N/A assertEquals(expType, inv.type());
5455N/A List<Object> targetPlusVarArgs = new ArrayList<>(targetPlusArgs);
2040N/A List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
2040N/A Object[] tail = tailList.toArray();
2040N/A tailList.clear(); tailList.add(tail);
3240N/A result = inv.invokeWithArguments(targetPlusVarArgs);
2040N/A if (testRetCode) assertEquals(code, result);
2040N/A assertCalled("invokee", args);
2040N/A }
3240N/A
2040N/A // dynamic invoker
2040N/A countTest();
3247N/A CallSite site = new MutableCallSite(type);
3247N/A inv = site.dynamicInvoker();
3240N/A
3240N/A // see if we get the result of the original target:
3240N/A try {
3240N/A result = inv.invokeWithArguments(args);
3240N/A assertTrue("should not reach here", false);
3240N/A } catch (IllegalStateException ex) {
3240N/A String msg = ex.getMessage();
3240N/A assertTrue(msg, msg.contains("site"));
3240N/A }
3240N/A
3240N/A // set new target after invoker is created, to make sure we track target
2040N/A site.setTarget(target);
2040N/A calledLog.clear();
3240N/A result = inv.invokeWithArguments(args);
2040N/A if (testRetCode) assertEquals(code, result);
2040N/A assertCalled("invokee", args);
2040N/A }
2040N/A
2040N/A static Object invokee(Object... args) {
2040N/A return called("invokee", args).hashCode();
2040N/A }
2040N/A
2038N/A private static final String MISSING_ARG = "missingArg";
5452N/A private static final String MISSING_ARG_2 = "missingArg#2";
2038N/A static Object targetIfEquals() {
2038N/A return called("targetIfEquals");
2038N/A }
2038N/A static Object fallbackIfNotEquals() {
2038N/A return called("fallbackIfNotEquals");
2038N/A }
2038N/A static Object targetIfEquals(Object x) {
2038N/A assertEquals(x, MISSING_ARG);
2038N/A return called("targetIfEquals", x);
2038N/A }
2038N/A static Object fallbackIfNotEquals(Object x) {
2038N/A assertFalse(x.toString(), x.equals(MISSING_ARG));
2038N/A return called("fallbackIfNotEquals", x);
2038N/A }
2038N/A static Object targetIfEquals(Object x, Object y) {
2038N/A assertEquals(x, y);
2038N/A return called("targetIfEquals", x, y);
2038N/A }
2038N/A static Object fallbackIfNotEquals(Object x, Object y) {
2038N/A assertFalse(x.toString(), x.equals(y));
2038N/A return called("fallbackIfNotEquals", x, y);
2038N/A }
2038N/A static Object targetIfEquals(Object x, Object y, Object z) {
2038N/A assertEquals(x, y);
2038N/A return called("targetIfEquals", x, y, z);
2038N/A }
2038N/A static Object fallbackIfNotEquals(Object x, Object y, Object z) {
2038N/A assertFalse(x.toString(), x.equals(y));
2038N/A return called("fallbackIfNotEquals", x, y, z);
2038N/A }
2038N/A
2040N/A @Test
2040N/A public void testGuardWithTest() throws Throwable {
2040N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("guardWithTest");
5452N/A for (int nargs = 0; nargs <= 50; nargs++) {
5452N/A if (CAN_TEST_LIGHTLY && nargs > 7) break;
2040N/A testGuardWithTest(nargs, Object.class);
2040N/A testGuardWithTest(nargs, String.class);
2040N/A }
2040N/A }
2040N/A void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
5452N/A testGuardWithTest(nargs, 0, argClass);
5452N/A if (nargs <= 5 || nargs % 10 == 3) {
5452N/A for (int testDrops = 1; testDrops <= nargs; testDrops++)
5452N/A testGuardWithTest(nargs, testDrops, argClass);
5452N/A }
5452N/A }
5452N/A void testGuardWithTest(int nargs, int testDrops, Class<?> argClass) throws Throwable {
2040N/A countTest();
5452N/A int nargs1 = Math.min(3, nargs);
2040N/A MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
5452N/A MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs1));
5452N/A MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs1));
2040N/A while (test.type().parameterCount() > nargs)
5452N/A // 0: test = constant(MISSING_ARG.equals(MISSING_ARG))
5452N/A // 1: test = lambda (_) MISSING_ARG.equals(_)
2040N/A test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
2040N/A if (argClass != Object.class) {
2040N/A test = changeArgTypes(test, argClass);
2040N/A target = changeArgTypes(target, argClass);
2040N/A fallback = changeArgTypes(fallback, argClass);
2040N/A }
5452N/A int testArgs = nargs - testDrops;
5452N/A assert(testArgs >= 0);
5452N/A test = addTrailingArgs(test, Math.min(testArgs, nargs), argClass);
5452N/A target = addTrailingArgs(target, nargs, argClass);
5452N/A fallback = addTrailingArgs(fallback, nargs, argClass);
2040N/A Object[][] argLists = {
2040N/A { },
2040N/A { "foo" }, { MISSING_ARG },
2040N/A { "foo", "foo" }, { "foo", "bar" },
2040N/A { "foo", "foo", "baz" }, { "foo", "bar", "baz" }
2040N/A };
2040N/A for (Object[] argList : argLists) {
5452N/A Object[] argList1 = argList;
5452N/A if (argList.length != nargs) {
5452N/A if (argList.length != nargs1) continue;
5452N/A argList1 = Arrays.copyOf(argList, nargs);
5452N/A Arrays.fill(argList1, nargs1, nargs, MISSING_ARG_2);
5452N/A }
5452N/A MethodHandle test1 = test;
5452N/A if (test1.type().parameterCount() > testArgs) {
5452N/A int pc = test1.type().parameterCount();
5452N/A test1 = MethodHandles.insertArguments(test, testArgs, Arrays.copyOfRange(argList1, testArgs, pc));
5452N/A }
5452N/A MethodHandle mh = MethodHandles.guardWithTest(test1, target, fallback);
5452N/A assertEquals(target.type(), mh.type());
2040N/A boolean equals;
2040N/A switch (nargs) {
2040N/A case 0: equals = true; break;
2040N/A case 1: equals = MISSING_ARG.equals(argList[0]); break;
2040N/A default: equals = argList[0].equals(argList[1]); break;
2040N/A }
2040N/A String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
2431N/A if (verbosity >= 3)
2040N/A System.out.println(logEntry(willCall, argList));
5452N/A Object result = mh.invokeWithArguments(argList1);
2040N/A assertCalled(willCall, argList);
2040N/A }
2040N/A }
2040N/A
2040N/A @Test
2040N/A public void testCatchException() throws Throwable {
2040N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("catchException");
5452N/A for (int nargs = 0; nargs < 40; nargs++) {
5459N/A if (CAN_TEST_LIGHTLY && nargs > 11) break;
5452N/A for (int throwMode = 0; throwMode < THROW_MODE_LIMIT; throwMode++) {
5452N/A testCatchException(int.class, new ClassCastException("testing"), throwMode, nargs);
5452N/A if (CAN_TEST_LIGHTLY && nargs > 3) continue;
5452N/A testCatchException(void.class, new java.io.IOException("testing"), throwMode, nargs);
5452N/A testCatchException(String.class, new LinkageError("testing"), throwMode, nargs);
2040N/A }
2040N/A }
2040N/A }
2040N/A
5452N/A static final int THROW_NOTHING = 0, THROW_CAUGHT = 1, THROW_UNCAUGHT = 2, THROW_THROUGH_ADAPTER = 3, THROW_MODE_LIMIT = 4;
5452N/A
5452N/A void testCatchException(Class<?> returnType, Throwable thrown, int throwMode, int nargs) throws Throwable {
5452N/A testCatchException(returnType, thrown, throwMode, nargs, 0);
5452N/A if (nargs <= 5 || nargs % 10 == 3) {
5452N/A for (int catchDrops = 1; catchDrops <= nargs; catchDrops++)
5452N/A testCatchException(returnType, thrown, throwMode, nargs, catchDrops);
5452N/A }
5452N/A }
5452N/A
2040N/A private static <T extends Throwable>
2040N/A Object throwOrReturn(Object normal, T exception) throws T {
5452N/A if (exception != null) {
5452N/A called("throwOrReturn/throw", normal, exception);
5452N/A throw exception;
5452N/A }
5452N/A called("throwOrReturn/normal", normal, exception);
2040N/A return normal;
2040N/A }
5452N/A private int fakeIdentityCount;
5452N/A private Object fakeIdentity(Object x) {
5452N/A System.out.println("should throw through this!");
5452N/A fakeIdentityCount++;
5452N/A return x;
5452N/A }
2040N/A
5452N/A void testCatchException(Class<?> returnType, Throwable thrown, int throwMode, int nargs, int catchDrops) throws Throwable {
2040N/A countTest();
2431N/A if (verbosity >= 3)
5452N/A System.out.println("catchException rt="+returnType+" throw="+throwMode+" nargs="+nargs+" drops="+catchDrops);
2040N/A Class<? extends Throwable> exType = thrown.getClass();
5452N/A if (throwMode > THROW_CAUGHT) thrown = new UnsupportedOperationException("do not catch this");
2040N/A MethodHandle throwOrReturn
2040N/A = PRIVATE.findStatic(MethodHandlesTest.class, "throwOrReturn",
2040N/A MethodType.methodType(Object.class, Object.class, Throwable.class));
5452N/A if (throwMode == THROW_THROUGH_ADAPTER) {
5452N/A MethodHandle fakeIdentity
5452N/A = PRIVATE.findVirtual(MethodHandlesTest.class, "fakeIdentity",
5452N/A MethodType.methodType(Object.class, Object.class)).bindTo(this);
5452N/A for (int i = 0; i < 10; i++)
5452N/A throwOrReturn = MethodHandles.filterReturnValue(throwOrReturn, fakeIdentity);
5452N/A }
5452N/A int nargs1 = Math.max(2, nargs);
3247N/A MethodHandle thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
5452N/A thrower = addTrailingArgs(thrower, nargs, Object.class);
5452N/A int catchArgc = 1 + nargs - catchDrops;
5452N/A MethodHandle catcher = varargsList(catchArgc).asType(MethodType.genericMethodType(catchArgc));
5452N/A Object[] args = randomArgs(nargs, Object.class);
5452N/A Object arg0 = MISSING_ARG;
5452N/A Object arg1 = (throwMode == THROW_NOTHING) ? (Throwable) null : thrown;
5452N/A if (nargs > 0) arg0 = args[0];
5452N/A if (nargs > 1) args[1] = arg1;
5452N/A assertEquals(nargs1, thrower.type().parameterCount());
5452N/A if (nargs < nargs1) {
5452N/A Object[] appendArgs = { arg0, arg1 };
5452N/A appendArgs = Arrays.copyOfRange(appendArgs, nargs, nargs1);
5452N/A thrower = MethodHandles.insertArguments(thrower, nargs, appendArgs);
5452N/A }
5452N/A assertEquals(nargs, thrower.type().parameterCount());
5452N/A MethodHandle target = MethodHandles.catchException(thrower, exType, catcher);
2040N/A assertEquals(thrower.type(), target.type());
5452N/A assertEquals(nargs, target.type().parameterCount());
2040N/A //System.out.println("catching with "+target+" : "+throwOrReturn);
5452N/A Object returned;
5452N/A try {
5452N/A returned = target.invokeWithArguments(args);
5452N/A } catch (Throwable ex) {
5452N/A assertSame("must get the out-of-band exception", thrown, ex);
5452N/A if (throwMode <= THROW_CAUGHT)
5452N/A assertEquals(THROW_UNCAUGHT, throwMode);
5452N/A returned = ex;
5452N/A }
5452N/A assertCalled("throwOrReturn/"+(throwMode == THROW_NOTHING ? "normal" : "throw"), arg0, arg1);
2040N/A //System.out.println("return from "+target+" : "+returned);
5452N/A if (throwMode == THROW_NOTHING) {
5452N/A assertSame(arg0, returned);
5452N/A } else if (throwMode == THROW_CAUGHT) {
5455N/A List<Object> catchArgs = new ArrayList<>(Arrays.asList(args));
5452N/A // catcher receives an initial subsequence of target arguments:
5452N/A catchArgs.subList(nargs - catchDrops, nargs).clear();
5452N/A // catcher also receives the exception, prepended:
2040N/A catchArgs.add(0, thrown);
2040N/A assertEquals(catchArgs, returned);
2040N/A }
5452N/A assertEquals(0, fakeIdentityCount);
2040N/A }
2040N/A
2040N/A @Test
2040N/A public void testThrowException() throws Throwable {
2040N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("throwException");
2040N/A testThrowException(int.class, new ClassCastException("testing"));
2040N/A testThrowException(void.class, new java.io.IOException("testing"));
2040N/A testThrowException(String.class, new LinkageError("testing"));
2040N/A }
2040N/A
2040N/A void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
2040N/A countTest();
2040N/A Class<? extends Throwable> exType = thrown.getClass();
2040N/A MethodHandle target = MethodHandles.throwException(returnType, exType);
2040N/A //System.out.println("throwing with "+target+" : "+thrown);
2040N/A MethodType expectedType = MethodType.methodType(returnType, exType);
2040N/A assertEquals(expectedType, target.type());
4250N/A target = target.asType(target.type().generic());
2040N/A Throwable caught = null;
2040N/A try {
2431N/A Object res = target.invokeExact((Object) thrown);
2040N/A fail("got "+res+" instead of throwing "+thrown);
2040N/A } catch (Throwable ex) {
2040N/A if (ex != thrown) {
2040N/A if (ex instanceof Error) throw (Error)ex;
2040N/A if (ex instanceof RuntimeException) throw (RuntimeException)ex;
2040N/A }
2040N/A caught = ex;
2040N/A }
2040N/A assertSame(thrown, caught);
2040N/A }
2040N/A
5462N/A @Test
5452N/A public void testInterfaceCast() throws Throwable {
5459N/A //if (CAN_SKIP_WORKING) return;
5459N/A startTest("interfaceCast");
5462N/A assert( (((Object)"foo") instanceof CharSequence));
5462N/A assert(!(((Object)"foo") instanceof Iterable));
5462N/A for (MethodHandle mh : new MethodHandle[]{
5462N/A MethodHandles.identity(String.class),
5462N/A MethodHandles.identity(CharSequence.class),
5462N/A MethodHandles.identity(Iterable.class)
5462N/A }) {
5462N/A if (verbosity > 0) System.out.println("-- mh = "+mh);
5462N/A for (Class<?> ctype : new Class<?>[]{
5462N/A Object.class, String.class, CharSequence.class,
5462N/A Number.class, Iterable.class
5462N/A }) {
5462N/A if (verbosity > 0) System.out.println("---- ctype = "+ctype.getName());
5462N/A // doret docast
5462N/A testInterfaceCast(mh, ctype, false, false);
5462N/A testInterfaceCast(mh, ctype, true, false);
5462N/A testInterfaceCast(mh, ctype, false, true);
5462N/A testInterfaceCast(mh, ctype, true, true);
5462N/A }
5452N/A }
5452N/A }
5462N/A private static Class<?> i2o(Class<?> c) {
5462N/A return (c.isInterface() ? Object.class : c);
5462N/A }
5462N/A public void testInterfaceCast(MethodHandle mh, Class<?> ctype,
5462N/A boolean doret, boolean docast) throws Throwable {
5462N/A MethodHandle mh0 = mh;
5462N/A if (verbosity > 1)
5462N/A System.out.println("mh="+mh+", ctype="+ctype.getName()+", doret="+doret+", docast="+docast);
5462N/A String normalRetVal = "normal return value";
5452N/A MethodType mt = mh.type();
5462N/A MethodType mt0 = mt;
5452N/A if (doret) mt = mt.changeReturnType(ctype);
5452N/A else mt = mt.changeParameterType(0, ctype);
5452N/A if (docast) mh = MethodHandles.explicitCastArguments(mh, mt);
5452N/A else mh = mh.asType(mt);
5462N/A assertEquals(mt, mh.type());
5462N/A MethodType mt1 = mt;
5452N/A // this bit is needed to make the interface types disappear for invokeWithArguments:
5452N/A mh = MethodHandles.explicitCastArguments(mh, mt.generic());
5462N/A Class<?>[] step = {
5462N/A mt1.parameterType(0), // param as passed to mh at first
5462N/A mt0.parameterType(0), // param after incoming cast
5462N/A mt0.returnType(), // return value before cast
5462N/A mt1.returnType(), // return value after outgoing cast
5462N/A };
5462N/A // where might a checkCast occur?
5462N/A boolean[] checkCast = new boolean[step.length];
5462N/A // the string value must pass each step without causing an exception
5462N/A if (!docast) {
5462N/A if (!doret) {
5462N/A if (step[0] != step[1])
5462N/A checkCast[1] = true; // incoming value is cast
5462N/A } else {
5462N/A if (step[2] != step[3])
5462N/A checkCast[3] = true; // outgoing value is cast
5462N/A }
5452N/A }
5462N/A boolean expectFail = false;
5462N/A for (int i = 0; i < step.length; i++) {
5462N/A Class<?> c = step[i];
5462N/A if (!checkCast[i]) c = i2o(c);
5462N/A if (!c.isInstance(normalRetVal)) {
5462N/A if (verbosity > 3)
5462N/A System.out.println("expect failure at step "+i+" in "+Arrays.toString(step)+Arrays.toString(checkCast));
5462N/A expectFail = true;
5462N/A break;
5462N/A }
5462N/A }
5462N/A countTest(!expectFail);
5462N/A if (verbosity > 2)
5462N/A System.out.println("expectFail="+expectFail+", mt="+mt);
5452N/A Object res;
5452N/A try {
5462N/A res = mh.invokeWithArguments(normalRetVal);
5452N/A } catch (Exception ex) {
5452N/A res = ex;
5452N/A }
5452N/A boolean sawFail = !(res instanceof String);
5452N/A if (sawFail != expectFail) {
5462N/A System.out.println("*** testInterfaceCast: mh0 = "+mh0);
5462N/A System.out.println(" retype using "+(docast ? "explicitCastArguments" : "asType")+" to "+mt+" => "+mh);
5462N/A System.out.println(" call returned "+res);
5462N/A System.out.println(" expected "+(expectFail ? "an exception" : normalRetVal));
5452N/A }
5462N/A if (!expectFail) {
5462N/A assertFalse(res.toString(), sawFail);
5462N/A assertEquals(normalRetVal, res);
5452N/A } else {
5462N/A assertTrue(res.toString(), sawFail);
5452N/A }
5452N/A }
5452N/A
5459N/A @Test // SLOW
2040N/A public void testCastFailure() throws Throwable {
2040N/A if (CAN_SKIP_WORKING) return;
2040N/A startTest("testCastFailure");
2040N/A testCastFailure("cast/argument", 11000);
5459N/A if (CAN_TEST_LIGHTLY) return;
2040N/A testCastFailure("unbox/argument", 11000);
2040N/A testCastFailure("cast/return", 11000);
2040N/A testCastFailure("unbox/return", 11000);
2040N/A }
2040N/A
3240N/A static class Surprise {
3011N/A public MethodHandle asMethodHandle() {
3011N/A return VALUE.bindTo(this);
3011N/A }
2040N/A Object value(Object x) {
2040N/A trace("value", x);
2040N/A if (boo != null) return boo;
2040N/A return x;
2040N/A }
2040N/A Object boo;
2040N/A void boo(Object x) { boo = x; }
2040N/A
2040N/A static void trace(String x, Object y) {
2040N/A if (verbosity > 8) System.out.println(x+"="+y);
2040N/A }
2040N/A static Object refIdentity(Object x) { trace("ref.x", x); return x; }
2040N/A static Integer boxIdentity(Integer x) { trace("box.x", x); return x; }
2040N/A static int intIdentity(int x) { trace("int.x", x); return x; }
3011N/A static MethodHandle VALUE, REF_IDENTITY, BOX_IDENTITY, INT_IDENTITY;
3011N/A static {
3011N/A try {
3011N/A VALUE = PRIVATE.findVirtual(
3011N/A Surprise.class, "value",
3011N/A MethodType.methodType(Object.class, Object.class));
3011N/A REF_IDENTITY = PRIVATE.findStatic(
3011N/A Surprise.class, "refIdentity",
3011N/A MethodType.methodType(Object.class, Object.class));
3011N/A BOX_IDENTITY = PRIVATE.findStatic(
3011N/A Surprise.class, "boxIdentity",
3011N/A MethodType.methodType(Integer.class, Integer.class));
3011N/A INT_IDENTITY = PRIVATE.findStatic(
3011N/A Surprise.class, "intIdentity",
3011N/A MethodType.methodType(int.class, int.class));
5455N/A } catch (NoSuchMethodException | IllegalAccessException ex) {
3011N/A throw new RuntimeException(ex);
3011N/A }
3011N/A }
2040N/A }
2040N/A
5455N/A @SuppressWarnings("ConvertToStringSwitch")
2040N/A void testCastFailure(String mode, int okCount) throws Throwable {
2040N/A countTest(false);
2431N/A if (verbosity > 2) System.out.println("mode="+mode);
2040N/A Surprise boo = new Surprise();
3011N/A MethodHandle identity = Surprise.REF_IDENTITY, surprise0 = boo.asMethodHandle(), surprise = surprise0;
2040N/A if (mode.endsWith("/return")) {
2040N/A if (mode.equals("unbox/return")) {
2040N/A // fail on return to ((Integer)surprise).intValue
4250N/A surprise = surprise.asType(MethodType.methodType(int.class, Object.class));
4250N/A identity = identity.asType(MethodType.methodType(int.class, Object.class));
2040N/A } else if (mode.equals("cast/return")) {
2040N/A // fail on return to (Integer)surprise
4250N/A surprise = surprise.asType(MethodType.methodType(Integer.class, Object.class));
4250N/A identity = identity.asType(MethodType.methodType(Integer.class, Object.class));
2040N/A }
2040N/A } else if (mode.endsWith("/argument")) {
2040N/A MethodHandle callee = null;
2040N/A if (mode.equals("unbox/argument")) {
2040N/A // fail on handing surprise to int argument
2040N/A callee = Surprise.INT_IDENTITY;
2040N/A } else if (mode.equals("cast/argument")) {
2040N/A // fail on handing surprise to Integer argument
2040N/A callee = Surprise.BOX_IDENTITY;
2040N/A }
2040N/A if (callee != null) {
4250N/A callee = callee.asType(MethodType.genericMethodType(1));
3240N/A surprise = MethodHandles.filterArguments(callee, 0, surprise);
3240N/A identity = MethodHandles.filterArguments(callee, 0, identity);
2040N/A }
2040N/A }
3011N/A assertNotSame(mode, surprise, surprise0);
4250N/A identity = identity.asType(MethodType.genericMethodType(1));
4250N/A surprise = surprise.asType(MethodType.genericMethodType(1));
2040N/A Object x = 42;
2040N/A for (int i = 0; i < okCount; i++) {
2431N/A Object y = identity.invokeExact(x);
2040N/A assertEquals(x, y);
2431N/A Object z = surprise.invokeExact(x);
2040N/A assertEquals(x, z);
2040N/A }
2040N/A boo.boo("Boo!");
2431N/A Object y = identity.invokeExact(x);
2040N/A assertEquals(x, y);
2040N/A try {
2431N/A Object z = surprise.invokeExact(x);
2040N/A System.out.println("Failed to throw; got z="+z);
2040N/A assertTrue(false);
4183N/A } catch (ClassCastException ex) {
2431N/A if (verbosity > 2)
2040N/A System.out.println("caught "+ex);
2431N/A if (verbosity > 3)
5459N/A ex.printStackTrace(System.out);
4183N/A assertTrue(true); // all is well
2040N/A }
2040N/A }
2040N/A
2432N/A static Example userMethod(Object o, String s, int i) {
2432N/A called("userMethod", o, s, i);
2432N/A return null;
2432N/A }
2432N/A
2432N/A @Test
2432N/A public void testUserClassInSignature() throws Throwable {
2432N/A if (CAN_SKIP_WORKING) return;
2432N/A startTest("testUserClassInSignature");
2432N/A Lookup lookup = MethodHandles.lookup();
2432N/A String name; MethodType mt; MethodHandle mh;
2432N/A Object[] args;
2432N/A
2432N/A // Try a static method.
2432N/A name = "userMethod";
2432N/A mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
2432N/A mh = lookup.findStatic(lookup.lookupClass(), name, mt);
2432N/A assertEquals(mt, mh.type());
2432N/A assertEquals(Example.class, mh.type().returnType());
2432N/A args = randomArgs(mh.type().parameterArray());
3240N/A mh.invokeWithArguments(args);
2432N/A assertCalled(name, args);
2432N/A
2432N/A // Try a virtual method.
2432N/A name = "v2";
2432N/A mt = MethodType.methodType(Object.class, Object.class, int.class);
2432N/A mh = lookup.findVirtual(Example.class, name, mt);
2432N/A assertEquals(mt, mh.type().dropParameterTypes(0,1));
2432N/A assertTrue(mh.type().parameterList().contains(Example.class));
2432N/A args = randomArgs(mh.type().parameterArray());
3240N/A mh.invokeWithArguments(args);
2432N/A assertCalled(name, args);
2432N/A }
3012N/A
3012N/A static void runForRunnable() {
3012N/A called("runForRunnable");
3012N/A }
4606N/A public interface Fooable {
5452N/A // overloads:
5455N/A Object foo(Object x, String y);
5455N/A List<?> foo(String x, int y);
5455N/A Object foo(String x);
3012N/A }
5452N/A static Object fooForFooable(String x, Object... y) {
5452N/A return called("fooForFooable/"+x, y);
3012N/A }
5455N/A @SuppressWarnings("serial") // not really a public API, just a test case
4606N/A public static class MyCheckedException extends Exception {
3012N/A }
4606N/A public interface WillThrow {
3012N/A void willThrow() throws MyCheckedException;
3012N/A }
5452N/A /*non-public*/ interface PrivateRunnable {
5452N/A public void run();
5452N/A }
3012N/A
3012N/A @Test
5452N/A public void testAsInterfaceInstance() throws Throwable {
3012N/A if (CAN_SKIP_WORKING) return;
5459N/A startTest("asInterfaceInstance");
3012N/A Lookup lookup = MethodHandles.lookup();
5452N/A // test typical case: Runnable.run
3012N/A {
5452N/A countTest();
5452N/A if (verbosity >= 2) System.out.println("Runnable");
3012N/A MethodType mt = MethodType.methodType(void.class);
3012N/A MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "runForRunnable", mt);
4250N/A Runnable proxy = MethodHandleProxies.asInterfaceInstance(Runnable.class, mh);
3012N/A proxy.run();
3012N/A assertCalled("runForRunnable");
3012N/A }
5452N/A // well known single-name overloaded interface: Appendable.append
3012N/A {
5452N/A countTest();
5452N/A if (verbosity >= 2) System.out.println("Appendable");
5455N/A ArrayList<List<?>> appendResults = new ArrayList<>();
5452N/A MethodHandle append = lookup.bind(appendResults, "add", MethodType.methodType(boolean.class, Object.class));
5452N/A append = append.asType(MethodType.methodType(void.class, List.class)); // specialize the type
5452N/A MethodHandle asList = lookup.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
5452N/A MethodHandle mh = MethodHandles.filterReturnValue(asList, append).asVarargsCollector(Object[].class);
5452N/A Appendable proxy = MethodHandleProxies.asInterfaceInstance(Appendable.class, mh);
5452N/A proxy.append("one");
5452N/A proxy.append("two", 3, 4);
5452N/A proxy.append('5');
5452N/A assertEquals(Arrays.asList(Arrays.asList("one"),
5452N/A Arrays.asList("two", 3, 4),
5452N/A Arrays.asList('5')),
5452N/A appendResults);
5452N/A if (verbosity >= 3) System.out.println("appendResults="+appendResults);
5452N/A appendResults.clear();
5452N/A Formatter formatter = new Formatter(proxy);
5452N/A String fmt = "foo str=%s char='%c' num=%d";
5452N/A Object[] fmtArgs = { "str!", 'C', 42 };
5452N/A String expect = String.format(fmt, fmtArgs);
5452N/A formatter.format(fmt, fmtArgs);
5452N/A String actual = "";
5452N/A if (verbosity >= 3) System.out.println("appendResults="+appendResults);
5455N/A for (List<?> l : appendResults) {
5452N/A Object x = l.get(0);
5452N/A switch (l.size()) {
5452N/A case 1: actual += x; continue;
5455N/A case 3: actual += ((String)x).substring((int)(Object)l.get(1), (int)(Object)l.get(2)); continue;
5452N/A }
5452N/A actual += l;
5452N/A }
5452N/A if (verbosity >= 3) System.out.println("expect="+expect);
5452N/A if (verbosity >= 3) System.out.println("actual="+actual);
5452N/A assertEquals(expect, actual);
5452N/A }
5452N/A // test case of an single name which is overloaded: Fooable.foo(...)
5452N/A {
5452N/A if (verbosity >= 2) System.out.println("Fooable");
5452N/A MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "fooForFooable",
5452N/A MethodType.methodType(Object.class, String.class, Object[].class));
4250N/A Fooable proxy = MethodHandleProxies.asInterfaceInstance(Fooable.class, mh);
5452N/A for (Method m : Fooable.class.getDeclaredMethods()) {
5452N/A countTest();
5452N/A assertSame("foo", m.getName());
5452N/A if (verbosity > 3)
5452N/A System.out.println("calling "+m);
5452N/A MethodHandle invoker = lookup.unreflect(m);
5452N/A MethodType mt = invoker.type();
5452N/A Class<?>[] types = mt.parameterArray();
5452N/A types[0] = int.class; // placeholder
5452N/A Object[] args = randomArgs(types);
5452N/A args[0] = proxy;
5452N/A if (verbosity > 3)
5452N/A System.out.println("calling "+m+" on "+Arrays.asList(args));
5452N/A Object result = invoker.invokeWithArguments(args);
5452N/A if (verbosity > 4)
5452N/A System.out.println("result = "+result);
5452N/A String name = "fooForFooable/"+args[1];
5452N/A Object[] argTail = Arrays.copyOfRange(args, 2, args.length);
5452N/A assertCalled(name, argTail);
5452N/A assertEquals(result, logEntry(name, argTail));
5452N/A }
3012N/A }
5452N/A // test processing of thrown exceptions:
3012N/A for (Throwable ex : new Throwable[] { new NullPointerException("ok"),
3012N/A new InternalError("ok"),
3012N/A new Throwable("fail"),
3012N/A new Exception("fail"),
3012N/A new MyCheckedException()
3012N/A }) {
3012N/A MethodHandle mh = MethodHandles.throwException(void.class, Throwable.class);
3012N/A mh = MethodHandles.insertArguments(mh, 0, ex);
4250N/A WillThrow proxy = MethodHandleProxies.asInterfaceInstance(WillThrow.class, mh);
3012N/A try {
5452N/A countTest();
3012N/A proxy.willThrow();
3012N/A System.out.println("Failed to throw: "+ex);
3012N/A assertTrue(false);
3012N/A } catch (Throwable ex1) {
5452N/A if (verbosity > 3) {
3012N/A System.out.println("throw "+ex);
3012N/A System.out.println("catch "+(ex == ex1 ? "UNWRAPPED" : ex1));
3012N/A }
3012N/A if (ex instanceof RuntimeException ||
3012N/A ex instanceof Error) {
3012N/A assertSame("must pass unchecked exception out without wrapping", ex, ex1);
3012N/A } else if (ex instanceof MyCheckedException) {
3012N/A assertSame("must pass declared exception out without wrapping", ex, ex1);
3012N/A } else {
3012N/A assertNotSame("must pass undeclared checked exception with wrapping", ex, ex1);
4606N/A if (!(ex1 instanceof UndeclaredThrowableException) || ex1.getCause() != ex) {
5459N/A ex1.printStackTrace(System.out);
4606N/A }
4606N/A assertSame(ex, ex1.getCause());
3012N/A UndeclaredThrowableException utex = (UndeclaredThrowableException) ex1;
3012N/A }
3012N/A }
3012N/A }
5452N/A // Test error checking on bad interfaces:
5455N/A for (Class<?> nonSMI : new Class<?>[] { Object.class,
3012N/A String.class,
3012N/A CharSequence.class,
5452N/A java.io.Serializable.class,
5452N/A PrivateRunnable.class,
3012N/A Example.class }) {
5452N/A if (verbosity > 2) System.out.println(nonSMI.getName());
3012N/A try {
5452N/A countTest(false);
5452N/A MethodHandleProxies.asInterfaceInstance(nonSMI, varargsArray(0));
5452N/A assertTrue("Failed to throw on "+nonSMI.getName(), false);
3012N/A } catch (IllegalArgumentException ex) {
5452N/A if (verbosity > 2) System.out.println(nonSMI.getSimpleName()+": "+ex);
5452N/A // Object: java.lang.IllegalArgumentException:
5452N/A // not a public interface: java.lang.Object
5452N/A // String: java.lang.IllegalArgumentException:
5452N/A // not a public interface: java.lang.String
5452N/A // CharSequence: java.lang.IllegalArgumentException:
5452N/A // not a single-method interface: java.lang.CharSequence
5452N/A // Serializable: java.lang.IllegalArgumentException:
5452N/A // not a single-method interface: java.io.Serializable
5452N/A // PrivateRunnable: java.lang.IllegalArgumentException:
5452N/A // not a public interface: test.java.lang.invoke.MethodHandlesTest$PrivateRunnable
5452N/A // Example: java.lang.IllegalArgumentException:
5452N/A // not a public interface: test.java.lang.invoke.MethodHandlesTest$Example
5452N/A }
5452N/A }
5452N/A // Test error checking on interfaces with the wrong method type:
5455N/A for (Class<?> intfc : new Class<?>[] { Runnable.class /*arity 0*/,
5452N/A Fooable.class /*arity 1 & 2*/ }) {
5452N/A int badArity = 1; // known to be incompatible
5452N/A if (verbosity > 2) System.out.println(intfc.getName());
5452N/A try {
5452N/A countTest(false);
5452N/A MethodHandleProxies.asInterfaceInstance(intfc, varargsArray(badArity));
5452N/A assertTrue("Failed to throw on "+intfc.getName(), false);
5452N/A } catch (WrongMethodTypeException ex) {
5452N/A if (verbosity > 2) System.out.println(intfc.getSimpleName()+": "+ex);
5452N/A // Runnable: java.lang.invoke.WrongMethodTypeException:
5452N/A // cannot convert MethodHandle(Object)Object[] to ()void
5452N/A // Fooable: java.lang.invoke.WrongMethodTypeException:
5452N/A // cannot convert MethodHandle(Object)Object[] to (Object,String)Object
3012N/A }
3012N/A }
3012N/A }
5453N/A
5453N/A @Test
5453N/A public void testRunnableProxy() throws Throwable {
5453N/A if (CAN_SKIP_WORKING) return;
5453N/A startTest("testRunnableProxy");
5453N/A MethodHandles.Lookup lookup = MethodHandles.lookup();
5453N/A MethodHandle run = lookup.findStatic(lookup.lookupClass(), "runForRunnable", MethodType.methodType(void.class));
5453N/A Runnable r = MethodHandleProxies.asInterfaceInstance(Runnable.class, run);
5453N/A testRunnableProxy(r);
5453N/A assertCalled("runForRunnable");
5453N/A }
5453N/A private static void testRunnableProxy(Runnable r) {
5453N/A //7058630: JSR 292 method handle proxy violates contract for Object methods
5453N/A r.run();
5453N/A Object o = r;
5453N/A r = null;
5453N/A boolean eq = (o == o);
5453N/A int hc = System.identityHashCode(o);
5453N/A String st = o.getClass().getName() + "@" + Integer.toHexString(hc);
5453N/A Object expect = Arrays.asList(st, eq, hc);
5453N/A if (verbosity >= 2) System.out.println("expect st/eq/hc = "+expect);
5453N/A Object actual = Arrays.asList(o.toString(), o.equals(o), o.hashCode());
5453N/A if (verbosity >= 2) System.out.println("actual st/eq/hc = "+actual);
5453N/A assertEquals(expect, actual);
5453N/A }
2038N/A}
3793N/A// Local abbreviated copy of sun.invoke.util.ValueConversions
5459N/A// This guy tests access from outside the same package member, but inside
5459N/A// the package itself.
2038N/Aclass ValueConversions {
2038N/A private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
2038N/A private static final Object[] NO_ARGS_ARRAY = {};
2038N/A private static Object[] makeArray(Object... args) { return args; }
2038N/A private static Object[] array() { return NO_ARGS_ARRAY; }
2038N/A private static Object[] array(Object a0)
2038N/A { return makeArray(a0); }
2038N/A private static Object[] array(Object a0, Object a1)
2038N/A { return makeArray(a0, a1); }
2038N/A private static Object[] array(Object a0, Object a1, Object a2)
2038N/A { return makeArray(a0, a1, a2); }
2038N/A private static Object[] array(Object a0, Object a1, Object a2, Object a3)
2038N/A { return makeArray(a0, a1, a2, a3); }
2038N/A private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2038N/A Object a4)
2038N/A { return makeArray(a0, a1, a2, a3, a4); }
2038N/A private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2038N/A Object a4, Object a5)
2038N/A { return makeArray(a0, a1, a2, a3, a4, a5); }
2038N/A private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2038N/A Object a4, Object a5, Object a6)
2038N/A { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
2038N/A private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2038N/A Object a4, Object a5, Object a6, Object a7)
2038N/A { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
2038N/A private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2038N/A Object a4, Object a5, Object a6, Object a7,
2038N/A Object a8)
2038N/A { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2038N/A private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2038N/A Object a4, Object a5, Object a6, Object a7,
2038N/A Object a8, Object a9)
2038N/A { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2038N/A static MethodHandle[] makeArrays() {
5455N/A ArrayList<MethodHandle> arrays = new ArrayList<>();
2038N/A MethodHandles.Lookup lookup = IMPL_LOOKUP;
2038N/A for (;;) {
2038N/A int nargs = arrays.size();
2040N/A MethodType type = MethodType.genericMethodType(nargs).changeReturnType(Object[].class);
2038N/A String name = "array";
2038N/A MethodHandle array = null;
2038N/A try {
2038N/A array = lookup.findStatic(ValueConversions.class, name, type);
3530N/A } catch (ReflectiveOperationException ex) {
3530N/A // break from loop!
2038N/A }
2038N/A if (array == null) break;
2038N/A arrays.add(array);
2038N/A }
3530N/A assertTrue(arrays.size() == 11); // current number of methods
2038N/A return arrays.toArray(new MethodHandle[0]);
2038N/A }
2038N/A static final MethodHandle[] ARRAYS = makeArrays();
2038N/A
2038N/A /** Return a method handle that takes the indicated number of Object
2038N/A * arguments and returns an Object array of them, as if for varargs.
2038N/A */
2038N/A public static MethodHandle varargsArray(int nargs) {
2038N/A if (nargs < ARRAYS.length)
2038N/A return ARRAYS[nargs];
4606N/A return MethodHandles.identity(Object[].class).asCollector(Object[].class, nargs);
2038N/A }
4183N/A public static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
4183N/A Class<?> elemType = arrayType.getComponentType();
4183N/A MethodType vaType = MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType));
4183N/A MethodHandle mh = varargsArray(nargs);
4183N/A if (arrayType != Object[].class)
4183N/A mh = MethodHandles.filterReturnValue(mh, CHANGE_ARRAY_TYPE.bindTo(arrayType));
4183N/A return mh.asType(vaType);
4183N/A }
4183N/A static Object changeArrayType(Class<?> arrayType, Object[] a) {
4183N/A Class<?> elemType = arrayType.getComponentType();
4183N/A if (!elemType.isPrimitive())
4183N/A return Arrays.copyOf(a, a.length, arrayType.asSubclass(Object[].class));
4183N/A Object b = java.lang.reflect.Array.newInstance(elemType, a.length);
4183N/A for (int i = 0; i < a.length; i++)
4183N/A java.lang.reflect.Array.set(b, i, a[i]);
4183N/A return b;
4183N/A }
4183N/A private static final MethodHandle CHANGE_ARRAY_TYPE;
4183N/A static {
4183N/A try {
4183N/A CHANGE_ARRAY_TYPE = IMPL_LOOKUP.findStatic(ValueConversions.class, "changeArrayType",
4183N/A MethodType.methodType(Object.class, Class.class, Object[].class));
4183N/A } catch (NoSuchMethodException | IllegalAccessException ex) {
4183N/A Error err = new InternalError("uncaught exception");
4183N/A err.initCause(ex);
4183N/A throw err;
4183N/A }
4183N/A }
2040N/A
2040N/A private static final List<Object> NO_ARGS_LIST = Arrays.asList(NO_ARGS_ARRAY);
2040N/A private static List<Object> makeList(Object... args) { return Arrays.asList(args); }
2040N/A private static List<Object> list() { return NO_ARGS_LIST; }
2040N/A private static List<Object> list(Object a0)
2040N/A { return makeList(a0); }
2040N/A private static List<Object> list(Object a0, Object a1)
2040N/A { return makeList(a0, a1); }
2040N/A private static List<Object> list(Object a0, Object a1, Object a2)
2040N/A { return makeList(a0, a1, a2); }
2040N/A private static List<Object> list(Object a0, Object a1, Object a2, Object a3)
2040N/A { return makeList(a0, a1, a2, a3); }
2040N/A private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2040N/A Object a4)
2040N/A { return makeList(a0, a1, a2, a3, a4); }
2040N/A private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2040N/A Object a4, Object a5)
2040N/A { return makeList(a0, a1, a2, a3, a4, a5); }
2040N/A private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2040N/A Object a4, Object a5, Object a6)
2040N/A { return makeList(a0, a1, a2, a3, a4, a5, a6); }
2040N/A private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2040N/A Object a4, Object a5, Object a6, Object a7)
2040N/A { return makeList(a0, a1, a2, a3, a4, a5, a6, a7); }
2040N/A private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2040N/A Object a4, Object a5, Object a6, Object a7,
2040N/A Object a8)
2040N/A { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2040N/A private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2040N/A Object a4, Object a5, Object a6, Object a7,
2040N/A Object a8, Object a9)
2040N/A { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2040N/A static MethodHandle[] makeLists() {
5455N/A ArrayList<MethodHandle> lists = new ArrayList<>();
2040N/A MethodHandles.Lookup lookup = IMPL_LOOKUP;
2040N/A for (;;) {
3529N/A int nargs = lists.size();
2040N/A MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
2040N/A String name = "list";
3529N/A MethodHandle list = null;
2040N/A try {
3529N/A list = lookup.findStatic(ValueConversions.class, name, type);
3530N/A } catch (ReflectiveOperationException ex) {
3530N/A // break from loop!
2040N/A }
3529N/A if (list == null) break;
3529N/A lists.add(list);
2040N/A }
3530N/A assertTrue(lists.size() == 11); // current number of methods
3529N/A return lists.toArray(new MethodHandle[0]);
2040N/A }
2040N/A static final MethodHandle[] LISTS = makeLists();
4606N/A static final MethodHandle AS_LIST;
4606N/A static {
4606N/A try {
4606N/A AS_LIST = IMPL_LOOKUP.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
5455N/A } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
4606N/A }
2040N/A
2040N/A /** Return a method handle that takes the indicated number of Object
2040N/A * arguments and returns List.
2040N/A */
2040N/A public static MethodHandle varargsList(int nargs) {
2040N/A if (nargs < LISTS.length)
2040N/A return LISTS[nargs];
4606N/A return AS_LIST.asCollector(Object[].class, nargs);
2040N/A }
2038N/A}
2038N/A// This guy tests access from outside the same package member, but inside
2038N/A// the package itself.
2038N/Aclass PackageSibling {
2038N/A static Lookup lookup() {
2038N/A return MethodHandles.lookup();
2038N/A }
2038N/A}