xref: /aosp_15_r20/art/test/2277-methodhandle-invokeexact/src/Main.java (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
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.WrongMethodTypeException;
19 import java.util.Objects;
20 import java.util.Optional;
21 
22 public class Main {
23 
main(String[] args)24   public static void main(String[] args) throws Throwable {
25     $noinline$testMethodHandleFromOtherDex();
26 
27     new ConstMethodHandleTest().runAll();
28     new JavaApiTest().runAll();
29   }
30 
$noinline$testMethodHandleFromOtherDex()31   private static void $noinline$testMethodHandleFromOtherDex() throws Throwable {
32     MethodHandle mh = Multi.$noinline$getMethodHandle();
33     Optional<String> nonEmpty = Optional.<String>of("hello");
34     Object returnedObject = mh.invokeExact(nonEmpty);
35     assertEquals("hello", returnedObject);
36 
37     try {
38       mh.invokeExact(nonEmpty);
39       unreachable("mh.type() is (Optional)Object, but callsite is (Optional)V");
40     } catch (WrongMethodTypeException expected) {}
41   }
42 
assertEquals(Object expected, Object actual)43   private static void assertEquals(Object expected, Object actual) {
44     if (!Objects.equals(expected, actual)) {
45       throw new AssertionError("Expected: " + expected + ", got: " + actual);
46     }
47   }
48 
unreachable(String msg)49   private static void unreachable(String msg) {
50     throw new AssertionError("Unexpectedly reached this point, but shouldn't: " + msg);
51   }
52 }
53