Example:
package com.example; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class Test { public interface A { void hello(); } private static void test(A a) { a.hello(); } public static void main(String[] args) { try { Class<?> AIntf = Class.forName("com.example.Test$A"); Object proxy = Proxy.newProxyInstance(AIntf.getClassLoader(), new Class[] { AIntf }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Hello World!"); return null; } }); test((A) proxy); } catch (Exception e) { e.printStackTrace(); } } }
Android-4.4中调用InputQueue的sendInputEvent注入Input事件:
Class<?> FinishedInputEventCallback = Class .forName("android.view.InputQueue$FinishedInputEventCallback"); Object proxy = Proxy.newProxyInstance(FinishedInputEventCallback.getClassLoader(), new Class[] { FinishedInputEventCallback }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return null; } }); call(mInputQueue, "sendInputEvent", new Class[] { InputEvent.class, Object.class, boolean.class, FinishedInputEventCallback }, new Object[] { event, null, false, proxy }); private static Object call(Object obj, String method, Class<?>[] argsType, Object[] args) { Object ret = null; if (obj == null) return ret; try { Class<?> c = obj.getClass(); Method m = c.getMethod(method, argsType); m.setAccessible(true); ret = m.invoke(obj, args); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return ret; }