1 /*
2  * Copyright (C) 2017 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.reflect.Method;
18 import java.lang.reflect.InvocationTargetException;
19 
20 class DebugProxy implements java.lang.reflect.InvocationHandler {
21     private Object obj;
22     static Class<?>[] interfaces = {Foo.class};
23 
newInstance(Object obj)24     public static Object newInstance(Object obj) {
25         return java.lang.reflect.Proxy.newProxyInstance(
26                 Foo.class.getClassLoader(), interfaces, new DebugProxy(obj));
27     }
28 
DebugProxy(Object obj)29     private DebugProxy(Object obj) {
30         this.obj = obj;
31     }
32 
invoke(Object proxy, Method m, Object[] args)33     public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
34         Object result;
35         if (obj == null) {
36             return null;
37         }
38         try {
39             System.out.println("before invoking method " + m.getName());
40             result = m.invoke(obj, args);
41         } catch (InvocationTargetException e) {
42             throw e.getTargetException();
43         } catch (Exception e) {
44             throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
45         } finally {
46             System.out.println("after invoking method " + m.getName());
47         }
48         return result;
49     }
50 }
51 
52 public class Main {
call(Foo foo)53     public static void call(Foo foo) {
54         if (foo == null) {
55             return;
56         }
57         foo.bar(null);
58     }
59 
main(String[] args)60     public static void main(String[] args) {
61         System.loadLibrary(args[0]);
62         Foo foo = (Foo)DebugProxy.newInstance(null);
63         ensureJitCompiled(Main.class, "call");
64         call(foo);
65     }
66 
ensureJitCompiled(Class<?> itf, String method_name)67     private static native void ensureJitCompiled(Class<?> itf, String method_name);
68 }
69