Path: blob/master/test/jdk/java/lang/invoke/InvokeGenericTest.java
41149 views
/*1* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/* @test24* @summary unit tests for java.lang.invoke.MethodHandle.invoke25* @compile InvokeGenericTest.java26* @run testng/othervm test.java.lang.invoke.InvokeGenericTest27*/2829package test.java.lang.invoke;3031import java.lang.invoke.*;32import static java.lang.invoke.MethodHandles.*;33import static java.lang.invoke.MethodType.*;34import java.lang.reflect.*;35import java.util.*;36import org.testng.*;37import static org.testng.AssertJUnit.*;38import org.testng.annotations.*;3940/**41*42* @author jrose43*/44@SuppressWarnings("cast") // various casts help emphasize arguments to invokeExact45public class InvokeGenericTest {46// How much output?47static int verbosity = 0;48static {49String vstr = System.getProperty("test.java.lang.invoke.InvokeGenericTest.verbosity");50if (vstr != null) verbosity = Integer.parseInt(vstr);51}5253// public static void main(String... av) throws Throwable {54// new InvokeGenericTest().testFirst();55// }5657@Test58public void testFirst() throws Throwable {59verbosity += 9; try {60// left blank for debugging61} finally { printCounts(); verbosity -= 9; }62}6364public InvokeGenericTest() {65}6667String testName;68static int allPosTests, allNegTests;69int posTests, negTests;70@AfterMethod71public void printCounts() {72if (verbosity >= 2 && (posTests | negTests) != 0) {73System.out.println();74if (posTests != 0) System.out.println("=== "+testName+": "+posTests+" positive test cases run");75if (negTests != 0) System.out.println("=== "+testName+": "+negTests+" negative test cases run");76allPosTests += posTests;77allNegTests += negTests;78posTests = negTests = 0;79}80}81void countTest(boolean positive) {82if (positive) ++posTests;83else ++negTests;84}85void countTest() { countTest(true); }86void startTest(String name) {87if (testName != null) printCounts();88if (verbosity >= 1)89System.out.println("["+name+"]");90posTests = negTests = 0;91testName = name;92}9394@BeforeClass95public static void setUpClass() throws Exception {96calledLog.clear();97calledLog.add(null);98nextArgVal = INITIAL_ARG_VAL;99}100101@AfterClass102public static void tearDownClass() throws Exception {103int posTests = allPosTests, negTests = allNegTests;104if (verbosity >= 2 && (posTests | negTests) != 0) {105System.out.println();106if (posTests != 0) System.out.println("=== "+posTests+" total positive test cases");107if (negTests != 0) System.out.println("=== "+negTests+" total negative test cases");108}109}110111static List<Object> calledLog = new ArrayList<>();112static Object logEntry(String name, Object... args) {113return Arrays.asList(name, Arrays.asList(args));114}115static Object called(String name, Object... args) {116Object entry = logEntry(name, args);117calledLog.add(entry);118return entry;119}120static void assertCalled(String name, Object... args) {121Object expected = logEntry(name, args);122Object actual = calledLog.get(calledLog.size() - 1);123if (expected.equals(actual) && verbosity < 9) return;124System.out.println("assertCalled "+name+":");125System.out.println("expected: "+expected);126System.out.println("actual: "+actual);127System.out.println("ex. types: "+getClasses(expected));128System.out.println("act. types: "+getClasses(actual));129assertEquals("previous method call", expected, actual);130}131static void printCalled(MethodHandle target, String name, Object... args) {132if (verbosity >= 3)133System.out.println("calling MH="+target+" to "+name+Arrays.toString(args));134}135136static Object castToWrapper(Object value, Class<?> dst) {137Object wrap = null;138if (value instanceof Number)139wrap = castToWrapperOrNull(((Number)value).longValue(), dst);140if (value instanceof Character)141wrap = castToWrapperOrNull((char)(Character)value, dst);142if (wrap != null) return wrap;143return dst.cast(value);144}145146static Object castToWrapperOrNull(long value, Class<?> dst) {147if (dst == int.class || dst == Integer.class)148return (int)(value);149if (dst == long.class || dst == Long.class)150return (long)(value);151if (dst == char.class || dst == Character.class)152return (char)(value);153if (dst == short.class || dst == Short.class)154return (short)(value);155if (dst == float.class || dst == Float.class)156return (float)(value);157if (dst == double.class || dst == Double.class)158return (double)(value);159if (dst == byte.class || dst == Byte.class)160return (byte)(value);161if (dst == boolean.class || dst == boolean.class)162return ((value % 29) & 1) == 0;163return null;164}165166static final int ONE_MILLION = (1000*1000), // first int value167TEN_BILLION = (10*1000*1000*1000), // scale factor to reach upper 32 bits168INITIAL_ARG_VAL = ONE_MILLION << 1; // <<1 makes space for sign bit;169static long nextArgVal;170static long nextArg(boolean moreBits) {171long val = nextArgVal++;172long sign = -(val & 1); // alternate signs173val >>= 1;174if (moreBits)175// Guarantee some bits in the high word.176// In any case keep the decimal representation simple-looking,177// with lots of zeroes, so as not to make the printed decimal178// strings unnecessarily noisy.179val += (val % ONE_MILLION) * TEN_BILLION;180return val ^ sign;181}182static int nextArg() {183// Produce a 32-bit result something like ONE_MILLION+(smallint).184// Example: 1_000_042.185return (int) nextArg(false);186}187static long nextArg(Class<?> kind) {188if (kind == long.class || kind == Long.class ||189kind == double.class || kind == Double.class)190// produce a 64-bit result something like191// ((TEN_BILLION+1) * (ONE_MILLION+(smallint)))192// Example: 10_000_420_001_000_042.193return nextArg(true);194return (long) nextArg();195}196197static Object randomArg(Class<?> param) {198Object wrap = castToWrapperOrNull(nextArg(param), param);199if (wrap != null) {200return wrap;201}202// import sun.invoke.util.Wrapper;203// Wrapper wrap = Wrapper.forBasicType(dst);204// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))205// wrap = Wrapper.forWrapperType(dst);206// if (wrap != Wrapper.OBJECT)207// return wrap.wrap(nextArg++);208if (param.isInterface()) {209for (Class<?> c : param.getClasses()) {210if (param.isAssignableFrom(c) && !c.isInterface())211{ param = c; break; }212}213}214if (param.isInterface() || param.isAssignableFrom(String.class))215return "#"+nextArg();216else217try {218return param.newInstance();219} catch (InstantiationException | IllegalAccessException ex) {220}221return null; // random class not Object, String, Integer, etc.222}223static Object[] randomArgs(Class<?>... params) {224Object[] args = new Object[params.length];225for (int i = 0; i < args.length; i++)226args[i] = randomArg(params[i]);227return args;228}229static Object[] randomArgs(int nargs, Class<?> param) {230Object[] args = new Object[nargs];231for (int i = 0; i < args.length; i++)232args[i] = randomArg(param);233return args;234}235236static final Object ANON_OBJ = new Object();237static Object zeroArg(Class<?> param) {238Object x = castToWrapperOrNull(0L, param);239if (x != null) return x;240if (param.isInterface() || param.isAssignableFrom(String.class)) return "\"\"";241if (param == Object.class) return ANON_OBJ;242if (param.getComponentType() != null) return Array.newInstance(param.getComponentType(), 0);243return null;244}245static Object[] zeroArgs(Class<?>... params) {246Object[] args = new Object[params.length];247for (int i = 0; i < args.length; i++)248args[i] = zeroArg(params[i]);249return args;250}251static Object[] zeroArgs(List<Class<?>> params) {252return zeroArgs(params.toArray(new Class<?>[0]));253}254255@SafeVarargs @SuppressWarnings("varargs")256static <T, E extends T> T[] array(Class<T[]> atype, E... a) {257return Arrays.copyOf(a, a.length, atype);258}259@SafeVarargs @SuppressWarnings("varargs")260static <T> T[] cat(T[] a, T... b) {261int alen = a.length, blen = b.length;262if (blen == 0) return a;263T[] c = Arrays.copyOf(a, alen + blen);264System.arraycopy(b, 0, c, alen, blen);265return c;266}267static Integer[] boxAll(int... vx) {268Integer[] res = new Integer[vx.length];269for (int i = 0; i < res.length; i++) {270res[i] = vx[i];271}272return res;273}274static Object getClasses(Object x) {275if (x == null) return x;276if (x instanceof String) return x; // keep the name277if (x instanceof List) {278// recursively report classes of the list elements279Object[] xa = ((List)x).toArray();280for (int i = 0; i < xa.length; i++)281xa[i] = getClasses(xa[i]);282return Arrays.asList(xa);283}284return x.getClass().getSimpleName();285}286287static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {288return changeArgTypes(target, 0, 999, argType);289}290static MethodHandle changeArgTypes(MethodHandle target,291int beg, int end, Class<?> argType) {292MethodType targetType = target.type();293end = Math.min(end, targetType.parameterCount());294ArrayList<Class<?>> argTypes = new ArrayList<>(targetType.parameterList());295Collections.fill(argTypes.subList(beg, end), argType);296MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);297return target.asType(ttype2);298}299300// This lookup is good for all members in and under InvokeGenericTest.301static final Lookup LOOKUP = MethodHandles.lookup();302303Map<List<Class<?>>, MethodHandle> CALLABLES = new HashMap<>();304MethodHandle callable(List<Class<?>> params) {305MethodHandle mh = CALLABLES.get(params);306if (mh == null) {307mh = collector_MH.asType(methodType(Object.class, params));308CALLABLES.put(params, mh);309}310return mh;311}312MethodHandle callable(Class<?>... params) {313return callable(Arrays.asList(params));314}315private static Object collector(Object... args) {316return Arrays.asList(args);317}318private static final MethodHandle collector_MH;319static {320try {321collector_MH322= LOOKUP.findStatic(LOOKUP.lookupClass(),323"collector",324methodType(Object.class, Object[].class));325} catch (ReflectiveOperationException ex) {326throw new RuntimeException(ex);327}328}329330@Test331public void testSimple() throws Throwable {332startTest("testSimple");333countTest();334String[] args = { "one", "two" };335MethodHandle mh = callable(Object.class, String.class);336Object res; List<?> resl;337res = resl = (List<?>) mh.invoke((String)args[0], (Object)args[1]);338//System.out.println(res);339assertEquals(Arrays.asList(args), res);340}341342@Test343public void testSimplePrims() throws Throwable {344startTest("testSimplePrims");345countTest();346int[] args = { 1, 2 };347MethodHandle mh = callable(Object.class, Object.class);348Object res; List<?> resl;349res = resl = (List<?>) mh.invoke(args[0], args[1]);350//System.out.println(res);351assertEquals(Arrays.toString(args), res.toString());352}353354@Test355public void testAlternateName() throws Throwable {356startTest("testAlternateName");357countTest();358String[] args = { "one", "two" };359MethodHandle mh = callable(Object.class, String.class);360Object res; List<?> resl;361res = resl = (List<?>) mh.invoke((String)args[0], (Object)args[1]);362//System.out.println(res);363assertEquals(Arrays.asList(args), res);364}365366@Test367public void testWrongArgumentCount() throws Throwable {368startTest("testWrongArgumentCount");369for (int i = 0; i <= 10; i++) {370testWrongArgumentCount(Collections.<Class<?>>nCopies(i, Integer.class));371if (i <= 4) {372testWrongArgumentCount(Collections.<Class<?>>nCopies(i, int.class));373testWrongArgumentCount(Collections.<Class<?>>nCopies(i, long.class));374}375}376}377public void testWrongArgumentCount(List<Class<?>> params) throws Throwable {378int max = params.size();379for (int i = 0; i < max; i++) {380List<Class<?>> params2 = params.subList(0, i);381for (int k = 0; k <= 2; k++) {382if (k == 1) params = methodType(Object.class, params).generic().parameterList();383if (k == 2) params2 = methodType(Object.class, params2).generic().parameterList();384testWrongArgumentCount(params, params2);385testWrongArgumentCount(params2, params);386}387}388}389public void testWrongArgumentCount(List<Class<?>> expect, List<Class<?>> observe) throws Throwable {390countTest(false);391if (expect.equals(observe))392assert(false);393MethodHandle target = callable(expect);394Object[] args = zeroArgs(observe);395Object junk;396try {397switch (args.length) {398case 0:399junk = target.invoke(); break;400case 1:401junk = target.invoke(args[0]); break;402case 2:403junk = target.invoke(args[0], args[1]); break;404case 3:405junk = target.invoke(args[0], args[1], args[2]); break;406case 4:407junk = target.invoke(args[0], args[1], args[2], args[3]); break;408default:409junk = target.invokeWithArguments(args); break;410}411} catch (WrongMethodTypeException ex) {412return;413} catch (Exception ex) {414throw new RuntimeException("wrong exception calling "+target+" on "+Arrays.asList(args), ex);415}416throw new RuntimeException("bad success calling "+target+" on "+Arrays.asList(args));417}418419/** Make a list of all combinations of the given types, with the given arities.420* A void return type is possible iff the first type is void.class.421*/422static List<MethodType> allMethodTypes(int minargc, int maxargc, Class<?>... types) {423ArrayList<MethodType> result = new ArrayList<>();424if (types.length > 0) {425ArrayList<MethodType> argcTypes = new ArrayList<>();426// build arity-zero types first427for (Class<?> rtype : types) {428argcTypes.add(MethodType.methodType(rtype));429}430if (types[0] == void.class)431// void is not an argument type432types = Arrays.copyOfRange(types, 1, types.length);433for (int argc = 0; argc <= maxargc; argc++) {434if (argc >= minargc)435result.addAll(argcTypes);436if (argc >= maxargc)437break;438ArrayList<MethodType> prevTypes = argcTypes;439argcTypes = new ArrayList<>();440for (MethodType prevType : prevTypes) {441for (Class<?> ptype : types) {442argcTypes.add(prevType.insertParameterTypes(argc, ptype));443}444}445}446}447return Collections.unmodifiableList(result);448}449static List<MethodType> allMethodTypes(int argc, Class<?>... types) {450return allMethodTypes(argc, argc, types);451}452453MethodHandle toString_MH;454455@Test456public void testReferenceConversions() throws Throwable {457startTest("testReferenceConversions");458toString_MH = LOOKUP.459findVirtual(Object.class, "toString", MethodType.methodType(String.class));460Object[] args = { "one", "two" };461for (MethodType type : allMethodTypes(2, Object.class, String.class, CharSequence.class)) {462testReferenceConversions(type, args);463}464}465public void testReferenceConversions(MethodType type, Object... args) throws Throwable {466countTest();467int nargs = args.length;468List<Object> argList = Arrays.asList(args);469String expectString = argList.toString();470if (verbosity > 3) System.out.println("target type: "+type+expectString);471MethodHandle mh = callable(type.parameterList());472mh = MethodHandles.filterReturnValue(mh, toString_MH);473mh = mh.asType(type);474Object res = null;475if (nargs == 2) {476res = mh.invoke((Object)args[0], (Object)args[1]);477assertEquals(expectString, res);478res = mh.invoke((String)args[0], (Object)args[1]);479assertEquals(expectString, res);480res = mh.invoke((Object)args[0], (String)args[1]);481assertEquals(expectString, res);482res = mh.invoke((String)args[0], (String)args[1]);483assertEquals(expectString, res);484res = mh.invoke((String)args[0], (CharSequence)args[1]);485assertEquals(expectString, res);486res = mh.invoke((CharSequence)args[0], (Object)args[1]);487assertEquals(expectString, res);488res = (String) mh.invoke((Object)args[0], (Object)args[1]);489assertEquals(expectString, res);490res = (String) mh.invoke((String)args[0], (Object)args[1]);491assertEquals(expectString, res);492res = (CharSequence) mh.invoke((String)args[0], (Object)args[1]);493assertEquals(expectString, res);494} else {495assert(false); // write this code496}497//System.out.println(res);498}499500501@Test502public void testBoxConversions() throws Throwable {503startTest("testBoxConversions");504countTest();505Object[] args = { 1, 2 };506MethodHandle mh = callable(Object.class, int.class);507Object res; List<?> resl; int resi;508res = resl = (List<?>) mh.invoke((int)args[0], (Object)args[1]);509//System.out.println(res);510assertEquals(Arrays.asList(args), res);511mh = MethodHandles.identity(int.class);512mh = MethodHandles.dropArguments(mh, 1, int.class);513res = resi = (int) mh.invoke((Object) args[0], (Object) args[1]);514assertEquals(args[0], res);515res = resi = (int) mh.invoke((int) args[0], (Object) args[1]);516assertEquals(args[0], res);517}518519}520521522