1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 import java.lang.invoke.MethodHandle; 18 import java.lang.invoke.MethodHandles; 19 import java.lang.invoke.MethodType; 20 import java.lang.invoke.WrongMethodTypeException; 21 import java.util.Objects; 22 import java.util.Optional; 23 24 public class Multi { $noinline$getMethodHandle()25 public static MethodHandle $noinline$getMethodHandle() { 26 return OPTIONAL_GET; 27 } 28 29 // MethodHandle comes from a different dex file. $noinline$testMHFromMain(MethodHandle mh)30 public static void $noinline$testMHFromMain(MethodHandle mh) throws Throwable { 31 Optional<Integer> nonEmpty = Optional.<Integer>of(1001); 32 Object result = (Object) mh.invokeExact(nonEmpty); 33 assertEquals("Expected 1001, but got " + result, 1001, result); 34 35 try { 36 mh.invokeExact(nonEmpty); 37 fail("mh.type() is (Optional)Object, but callsite is (Optional)V"); 38 } catch (WrongMethodTypeException expected) {} 39 } 40 assertEquals(String msg, Object expected, Object actual)41 private static void assertEquals(String msg, Object expected, Object actual) { 42 if (!Objects.equals(expected, actual)) { 43 fail(msg); 44 } 45 } 46 fail(String msg)47 private static void fail(String msg) { 48 throw new AssertionError(msg); 49 } 50 51 private static final MethodHandle OPTIONAL_GET; 52 53 static { 54 try { 55 OPTIONAL_GET = MethodHandles.lookup() 56 .findVirtual(Optional.class, "get", MethodType.methodType(Object.class)); 57 } catch (Throwable t) { 58 throw new RuntimeException(t); 59 } 60 } 61 } 62