1 /* 2 * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 /* 25 * @test 26 * @summary Smoke test for captured values in quoted lambdas. 27 * @run testng TestCaptureQuoted 28 */ 29 30 import java.lang.reflect.code.op.CoreOp.Var; 31 import java.lang.reflect.code.Op; 32 import java.lang.reflect.code.Quoted; 33 import java.lang.reflect.code.interpreter.Interpreter; 34 import java.lang.invoke.MethodHandles; 35 import java.util.stream.IntStream; 36 37 import org.testng.annotations.*; 38 import static org.testng.Assert.*; 39 40 public class TestCaptureQuoted { 41 42 @Test(dataProvider = "ints") 43 public void testCaptureIntParam(int x) { 44 Quoted quoted = (int y) -> x + y; 45 assertEquals(quoted.capturedValues().size(), 1); 46 assertEquals(((Var)quoted.capturedValues().values().iterator().next()).value(), x); 47 int res = (int)Interpreter.invoke(MethodHandles.lookup(), (Op & Op.Invokable) quoted.op(), 48 quoted.capturedValues(), 1); 49 assertEquals(res, x + 1); 50 } 51 52 @Test(dataProvider = "ints") 53 public void testCaptureIntField(int x) { 54 class Context { 55 final int x; 56 57 Context(int x) { 58 this.x = x; 59 } 60 61 Quoted quoted() { 62 return (int y) -> x + y; 63 } 64 } 65 Context context = new Context(x); 66 Quoted quoted = context.quoted(); 67 assertEquals(quoted.capturedValues().size(), 1); 68 assertEquals(quoted.capturedValues().values().iterator().next(), context); 69 int res = (int)Interpreter.invoke(MethodHandles.lookup(), (Op & Op.Invokable) quoted.op(), 70 quoted.capturedValues(), 1); 71 assertEquals(res, x + 1); 72 } 73 74 @DataProvider(name = "ints") 75 public Object[][] ints() { 76 return IntStream.range(0, 50) 77 .mapToObj(i -> new Object[] { i }) 78 .toArray(Object[][]::new); 79 } 80 }