public Object invoke(Object target, Method method, Object[] params) throws Throwable { if (EQUALS_METHOD.equals(method)) { Object param = params[0]; if (param == null || !Proxy.isProxyClass(param.getClass())) { return false; } InvocationHandler other = Proxy.getInvocationHandler(param); return equals(other); } else if (HASHCODE_METHOD.equals(method)) { return hashCode(); } MethodInvocation invocation = new MethodInvocation(method.getName(), method.getReturnType(), method.getGenericReturnType(), method.getParameterTypes(), target, targetType, sourceObject, params); invoker.invoke(invocation); if (!invocation.found()) { String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName() + "()"; throw Exceptions.unsupportedMethod(methodName); } return invocation.getResult(); }
private static void enableFullScreen(Window window) { try { Class fullScreenUtilities = Class.forName("com.apple.eawt.FullScreenUtilities"); Method setWindowCanFullScreen = fullScreenUtilities.getMethod("setWindowCanFullScreen", Window.class, boolean.class); setWindowCanFullScreen.invoke(fullScreenUtilities, window, true); Class fullScreenListener = Class.forName("com.apple.eawt.FullScreenListener"); Object listenerObject = Proxy.newProxyInstance(fullScreenListener.getClassLoader(), new Class[]{fullScreenListener}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { switch (method.getName()) { case "windowEnteringFullScreen": windowEnteringFullScreen = true; break; case "windowEnteredFullScreen": windowEnteredFullScreen = true; break; } return null; } }); Method addFullScreenListener = fullScreenUtilities.getMethod("addFullScreenListenerTo", Window.class, fullScreenListener); addFullScreenListener.invoke(fullScreenUtilities, window, listenerObject); } catch (Exception e) { throw new RuntimeException("FullScreen utilities not available", e); } }
public Class<?> defineClass(Class clazz, InvocationHandler invocationHandler) throws ClassNotFoundException { String clazzName = replaceClassName(clazz) + ".class"; try { ClassWriter cw = new ClassWriter(0); //读取 被代理类 InputStream is = clazz.getClassLoader().getResourceAsStream(clazzName); ClassReader reader = new ClassReader(is); reader.accept(new AopClassAdapter(ASM5, cw, invocationHandler), ClassReader.SKIP_DEBUG); byte[] code = cw.toByteArray(); FileOutputStream fos = new FileOutputStream(AopClassLoader.class.getResource("").getPath().toString() + "/Asm_Tmp.class"); fos.write(code); fos.flush(); fos.close(); return super.defineClass(clazz.getName() + "$simplify", code, 0, code.length); } catch (Throwable e) { System.out.println(e); throw new ClassNotFoundException(); } }
public Connection connect(String url, Properties info) throws SQLException { return (Connection)Proxy.newProxyInstance(DriverImpl.class.getClassLoader(), new Class[] { ConnectionEx.class }, new InvocationHandler() { public Object invoke(Object proxy, Method m, Object[] args) { String methodName = m.getName(); if (methodName.equals("getDriver")) { return DriverImpl.this; } else if (methodName.equals("hashCode")) { Integer i = new Integer(System.identityHashCode(proxy)); return i; } else if (methodName.equals("equals")) { return Boolean.valueOf(proxy == args[0]); } return null; } }); }
private static Object generateProxyType(final int i) { class DummyH implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("equals")) { return proxy == args[0]; } if (method.getName().equals("toString")) { return "DummyH[" + i + "]"; } return null; } } return Proxy.newProxyInstance( MetaInfCache.class.getClassLoader(), findTypes(i), new DummyH() ); }
@Override public void afterPropertiesSet() throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // 加载Iface接口 objectClass = classLoader.loadClass(serverAddressProvider.getService() + "$Iface"); // 加载Client.Factory类 Class<TServiceClientFactory<TServiceClient>> fi = (Class<TServiceClientFactory<TServiceClient>>) classLoader. loadClass(serverAddressProvider.getService() + "$Client$Factory"); TServiceClientFactory<TServiceClient> clientFactory = fi.newInstance(); ThriftClientPoolFactory clientPool = new ThriftClientPoolFactory(serverAddressProvider, clientFactory, callback); pool = new GenericObjectPool<TServiceClient>(clientPool, makePoolConfig()); // InvocationHandler handler = makeProxyHandler();//方式1 InvocationHandler handler = makeProxyHandler2();//方式2 proxyClient = Proxy.newProxyInstance(classLoader, new Class[] { objectClass }, handler); }
public Object getObject(final String command) throws Exception { Object templatesImpl = Gadgets.createTemplatesImpl(command); // inert chain for setup final Transformer transformerChain = new ChainedTransformer( new Transformer[]{ new ConstantTransformer(1) }); // real chain for after setup final Transformer[] transformers = new Transformer[] { new ConstantTransformer(TrAXFilter.class), new InstantiateTransformer( new Class[] { Templates.class }, new Object[] { templatesImpl } )}; final Map innerMap = new HashMap(); final Map lazyMap = LazyMap.decorate(innerMap, transformerChain); final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class); final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy); Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain return handler; }
@Override protected Object getInterfaceProxyHelper(ContextFactory cf, Class<?>[] interfaces) { // XXX: How to handle interfaces array withclasses from different // class loaders? Using cf.getApplicationClassLoader() ? ClassLoader loader = interfaces[0].getClassLoader(); Class<?> cl = Proxy.getProxyClass(loader, interfaces); Constructor<?> c; try { c = cl.getConstructor(new Class[] { InvocationHandler.class }); } catch (NoSuchMethodException ex) { // Should not happen throw Kit.initCause(new IllegalStateException(), ex); } return c; }
public HookHandler(IBinder base, Class<?> stubClass, InvocationHandler InvocationHandler) { mInvocationHandler = InvocationHandler; try { Method asInterface = stubClass.getDeclaredMethod("asInterface", IBinder.class); this.mBase = asInterface.invoke(null, base); Class clazz = mBase.getClass(); Field mRemote = clazz.getDeclaredField("mRemote"); mRemote.setAccessible(true); //新建一个 BinderProxy 的代理对象 Object binderProxy = Proxy.newProxyInstance(mBase.getClass().getClassLoader(), new Class[] {IBinder.class}, new TransactionWatcherHook((IBinder) mRemote.get(mBase), (IInterface) mBase)); mRemote.set(mBase, binderProxy); } catch (Exception e) { e.printStackTrace(); } }
public <T> T create(final Class<T> service) { if(!service.isInterface()){ throw new IllegalArgumentException("service must be an interface"); } return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { AbstractRemoteHandler handler = handlerFor(method); if(handler == null){ return null; } return handler.invoke(args[0]); } }); }
@Test public void testProvideInvocationHandlerFactory() throws Exception { server.enqueue(new MockResponse().setBody("response data")); String url = "http://localhost:" + server.getPort(); final AtomicInteger callCount = new AtomicInteger(); InvocationHandlerFactory factory = new InvocationHandlerFactory() { private final InvocationHandlerFactory delegate = new Default(); @Override public InvocationHandler create(Target target, Map<Method, MethodHandler> dispatch) { callCount.incrementAndGet(); return delegate.create(target, dispatch); } }; TestInterface api = Feign.builder().invocationHandlerFactory(factory).target(TestInterface.class, url); Response response = api.codecPost("request data"); assertEquals("response data", Util.toString(response.body().asReader())); assertEquals(1, callCount.get()); assertThat(server.takeRequest()) .hasBody("request data"); }
@Override public IBinder getService(final Context context, ClassLoader classLoader, IBinder binder) { return new StubBinder(classLoader, binder) { @Override public InvocationHandler createHandler(Class<?> interfaceClass, final IInterface base) { return new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return method.invoke(base, args); } catch (InvocationTargetException e) { if (e.getCause() != null) { throw e.getCause(); } throw e; } } }; } }; }
/** * Generate proxy arrays. */ Proxy[][] genArrays(int size, int narrays) throws Exception { Class proxyClass = Proxy.getProxyClass(DummyInterface.class.getClassLoader(), new Class[] { DummyInterface.class }); Constructor proxyCons = proxyClass.getConstructor(new Class[] { InvocationHandler.class }); Object[] consArgs = new Object[] { new DummyHandler() }; Proxy[][] arrays = new Proxy[narrays][size]; for (int i = 0; i < narrays; i++) { for (int j = 0; j < size; j++) { arrays[i][j] = (Proxy) proxyCons.newInstance(consArgs); } } return arrays; }
private void newInstanceFromConstructor(Class<?> proxyClass) throws Exception { // expect newInstance to succeed if it's in the same runtime package boolean isSamePackage = proxyClass.getName().lastIndexOf('.') == -1; try { Constructor cons = proxyClass.getConstructor(InvocationHandler.class); cons.newInstance(newInvocationHandler()); if (!isSamePackage) { throw new RuntimeException("ERROR: Constructor.newInstance should not succeed"); } } catch (IllegalAccessException e) { if (isSamePackage) { throw e; } } }
private InvocationHandler createInvocationHandler(final Object instance) { return new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(!shouldTrace(method)) { return method.invoke(instance, args); } SpanBuilder span = tracer.createSpan(); try { return method.invoke(instance, args); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); span.exception(cause); throw cause; } finally { span.resource(method.getDeclaringClass().getCanonicalName()).operation(method.getName()); tracer.closeSpan(span); } } }; }
public Object getObject ( final String command ) throws Exception { final Object templates = Gadgets.createTemplatesImpl(command); AdvisedSupport as = new AdvisedSupport(); as.setTargetSource(new SingletonTargetSource(templates)); final Type typeTemplatesProxy = Gadgets.createProxy( (InvocationHandler) Reflections.getFirstCtor("org.springframework.aop.framework.JdkDynamicAopProxy").newInstance(as), Type.class, Templates.class); final Object typeProviderProxy = Gadgets.createMemoitizedProxy( Gadgets.createMap("getType", typeTemplatesProxy), forName("org.springframework.core.SerializableTypeWrapper$TypeProvider")); Object mitp = Reflections.createWithoutConstructor(forName("org.springframework.core.SerializableTypeWrapper$MethodInvokeTypeProvider")); Reflections.setFieldValue(mitp, "provider", typeProviderProxy); Reflections.setFieldValue(mitp, "methodName", "newTransformer"); return mitp; }
private <T> T createEndpointIFBaseProxy(@Nullable WSEndpointReference epr, QName portName, Class<T> portInterface, WebServiceFeatureList webServiceFeatures, SEIPortInfo eif) { //fail if service doesnt have WSDL if (wsdlService == null) { throw new WebServiceException(ClientMessages.INVALID_SERVICE_NO_WSDL(serviceName)); } if (wsdlService.get(portName)==null) { throw new WebServiceException( ClientMessages.INVALID_PORT_NAME(portName,buildWsdlPortNames())); } BindingImpl binding = eif.createBinding(webServiceFeatures, portInterface); InvocationHandler pis = getStubHandler(binding, eif, epr); T proxy = createProxy(portInterface, pis); if (serviceInterceptor != null) { serviceInterceptor.postCreateProxy((WSBindingProvider)proxy, portInterface); } return proxy; }
/** * Construct a collection of Policy implementations for the specified binding * * @param binding the binding * @return the collection of policy implementations */ @SuppressWarnings("unchecked") public Collection<P> createList(B binding) { Collection<BehaviourDefinition> behaviourDefs = index.find(binding); List<P> policyInterfaces = new ArrayList<P>(behaviourDefs.size()); for (BehaviourDefinition behaviourDef : behaviourDefs) { Behaviour behaviour = behaviourDef.getBehaviour(); P policyIF = behaviour.getInterface(policyClass); if (!(behaviour.getNotificationFrequency().equals(NotificationFrequency.EVERY_EVENT))) { // wrap behaviour in transaction proxy which deals with delaying invocation until necessary if (transactionHandlerFactory == null) { throw new PolicyException("Transaction-level policies not supported as transaction support for the Policy Component has not been initialised."); } InvocationHandler trxHandler = transactionHandlerFactory.createHandler(behaviour, behaviourDef.getPolicyDefinition(), policyIF); policyIF = (P)Proxy.newProxyInstance(policyClass.getClassLoader(), new Class[]{policyClass}, trxHandler); } policyInterfaces.add(policyIF); } return policyInterfaces; }
/** Quartz-1.6.x wraps the original Connection inside a Proxy. * This method will extract the original Connection, allowing access to vendor specific operations */ private Connection extractWrappedConnection(Connection conn) { if (conn instanceof Proxy) { try { if (log.isDebugEnabled()) log.debug("Extracting a WrappedConnection from the Proxy: " + conn); Proxy connProxy = (Proxy) conn; InvocationHandler invocationHandler = Proxy.getInvocationHandler(connProxy); Method m = invocationHandler.getClass().getMethod("getWrappedConnection"); if (Connection.class.isAssignableFrom(m.getReturnType())) { Connection wrappedConnection = (Connection) m.invoke(invocationHandler); if (log.isDebugEnabled()) log.debug("Extracted WrappedConnection: " + wrappedConnection); return wrappedConnection; } else { if (log.isDebugEnabled()) log.debug("WrappedConnection cannot be extracted since the method 'public Connection getWrappedConnection()' is missing from the InvocationHandler: " + invocationHandler); } } catch (Exception e) { // do nothing if (log.isDebugEnabled()) log.debug("Exception in obtaining the WrappedConnection from the Proxy: " + conn, e); } } return conn; }
public Object getObject ( CmdExecuteHelper cmdHelper ) throws Exception { final Object templates = Gadgets.createTemplatesImpl(cmdHelper.getCommandArray()); AdvisedSupport as = new AdvisedSupport(); as.setTargetSource(new SingletonTargetSource(templates)); final Type typeTemplatesProxy = Gadgets.createProxy( (InvocationHandler) Reflections.getFirstCtor("org.springframework.aop.framework.JdkDynamicAopProxy").newInstance(as), Type.class, Templates.class); final Object typeProviderProxy = Gadgets.createMemoitizedProxy( Gadgets.createMap("getType", typeTemplatesProxy), forName("org.springframework.core.SerializableTypeWrapper$TypeProvider")); Object mitp = Reflections.createWithoutConstructor(forName("org.springframework.core.SerializableTypeWrapper$MethodInvokeTypeProvider")); Reflections.setFieldValue(mitp, "provider", typeProviderProxy); Reflections.setFieldValue(mitp, "methodName", "newTransformer"); return mitp; }
@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety. private <T> T create(final Class<T> service, final Wrapper wrapper, final Interceptor interceptor) { Object proxyInstance = Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object... args) throws Throwable { if (method.getDeclaringClass() == Object.class) { // filter Object method return method.invoke(this, args); } wrapper.setMethod(method); wrapper.setMethodArgs(args); Class returnType = method.getReturnType(); if (returnType == void.class) { if (interceptor == null || !interceptor.intercept(wrapper)) { wrapper.start(); } return null; } else if (returnType == Wrapper.class) { return wrapper; } else { throw new RuntimeException("method return type only support 'void' or 'Wrapper'"); } } }); return (T) proxyInstance; }
@SuppressWarnings("rawtypes") public static Object adapt(Object t) { if (!Proxy.isProxyClass(t.getClass())) { return t; } InvocationHandler ih = Proxy.getInvocationHandler(t); if (ih == null) { return t; } if (!JDKProxyInvokeHandler.class.isAssignableFrom(ih.getClass())) { return t; } JDKProxyInvokeHandler jpih = (JDKProxyInvokeHandler) ih; return jpih.getTarget(); }
/** * 获取代理对象, jdk的代理对象只能强转成父类才能正常使用, 所以他必须实现一个接口 * @param target 被代理的对象Class * @param h 代理的具体操作在此对象的invoke方法内进行 * @return jdk的代理对象 */ public static Object getProxy(Class<?> target, InvocationHandler h) { Class<?>[] interfaces = null; if (target.isInterface()) { interfaces = new Class<?>[]{target}; } if (interfaces == null) { interfaces = target.getInterfaces(); if (interfaces.length == 0) { throw new IllegalArgumentException("target必须为接口或者接口的实现类"); } } return Proxy.newProxyInstance(BasicUtil.getDefaultClassLoad(), interfaces, h); }
public Object getObject(CmdExecuteHelper cmdHelper) throws Exception { final Object templates = Gadgets.createTemplatesImpl(cmdHelper.getCommandArray()); String zeroHashCodeStr = "f5a5a608"; HashMap map = new HashMap(); map.put(zeroHashCodeStr, "foo"); InvocationHandler tempHandler = (InvocationHandler) Reflections.getFirstCtor(Gadgets.ANN_INV_HANDLER_CLASS).newInstance(Override.class, map); Reflections.setFieldValue(tempHandler, "type", Templates.class); Templates proxy = Gadgets.createProxy(tempHandler, Templates.class); LinkedHashSet set = new LinkedHashSet(); // maintain order set.add(templates); set.add(proxy); Reflections.setFieldValue(templates, "_auxClasses", null); Reflections.setFieldValue(templates, "_class", null); map.put(zeroHashCodeStr, templates); // swap in real object return set; }
/** * {@inheritDoc} */ @Override public Object getObject() throws Exception { InvocationHandler invocationHandler = (proxy, method, args) -> { if (isToString(method)) { return "LepService proxy for: " + getObjectType().getCanonicalName(); } else if (isObjectMethod(method)) { // other objects methods return method.invoke(proxy, args); } // execute LEP method return lepServiceHandler.onMethodInvoke(type, null, method, args); }; return Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, invocationHandler); }
public static <T> T getShowMethodInfoProxy(final T realObj){ return (T) Proxy.newProxyInstance(ProxyTools.class.getClassLoader(), realObj.getClass().getInterfaces(), new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { XLog.e("method name:"+ method.getName() + "--args:"+ Arrays.toString(args)); Object o = method.invoke(realObj,args); return o; } }); }
private boolean isProxyForSameRubyObject(Object other) { if (!Proxy.isProxyClass(other.getClass())) { return false; } InvocationHandler ih = Proxy.getInvocationHandler(other); return (ih instanceof RubyObjectInvocationHandler && this.rubyObject.equals(((RubyObjectInvocationHandler) ih).rubyObject)); }
protected Object wrapDataSource(Object datasource, String username, String password) throws NamingException { try { Class<?> proxyClass = Proxy.getProxyClass(datasource.getClass().getClassLoader(), datasource.getClass().getInterfaces()); Constructor<?> proxyConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class }); DataSourceHandler handler = new DataSourceHandler((DataSource)datasource, username, password); return proxyConstructor.newInstance(handler); }catch (Exception x) { if (x instanceof InvocationTargetException) { Throwable cause = x.getCause(); if (cause instanceof ThreadDeath) { throw (ThreadDeath) cause; } if (cause instanceof VirtualMachineError) { throw (VirtualMachineError) cause; } if (cause instanceof Exception) { x = (Exception) cause; } } if (x instanceof NamingException) throw (NamingException)x; else { NamingException nx = new NamingException(x.getMessage()); nx.initCause(x); throw nx; } } }
@VisibleForTesting static boolean isRpcInvocation(Object proxy) { if (proxy instanceof ProtocolTranslator) { proxy = ((ProtocolTranslator) proxy).getUnderlyingProxyObject(); } if (!Proxy.isProxyClass(proxy.getClass())) { return false; } final InvocationHandler ih = Proxy.getInvocationHandler(proxy); return ih instanceof RpcInvocationHandler; }
private static Object wrap(Class<?> clazz, ConnectionHandle c, Object h, List<InvocationHandler> subHandlers) { if (h == null) { return null; } InvocationHandler ih = (proxy, method, args) -> { try { for (InvocationHandler sih : subHandlers) { Object o = sih.invoke(proxy, method, args); if (o != UNHANLED) { return o; } } Object result = method.invoke(h, args); if (CLASSES_TO_WRAP.contains(method.getReturnType())) { result = wrap(method.getReturnType(), c, result, Arrays.asList(wrapperIh(result), statementIh(c, result), getConnectionIh(c))); } return result; } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t instanceof Exception) { c.connectionError((Exception) t); } throw e; } }; return Proxy.newProxyInstance(h.getClass().getClassLoader(), new Class[] { clazz }, ih); }
public static ResultSet newResultSet(final Object... defs) throws NoSuchMethodException, SecurityException { if (defs.length % 2 != 0) { throw new IllegalArgumentException(); } Method wasNull = ResultSet.class.getMethod("wasNull"); Map<Method, Object> values = new HashMap<>(); for (int i = 0; i < defs.length; i += 2) { Method target = defs[i].equals("wasNull") ? wasNull : ResultSet.class.getMethod(defs[i].toString(), int.class); values.put(target, defs[i + 1]); } AtomicBoolean flg = new AtomicBoolean(false); InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { if (values.containsKey(method)) { Object o = values.get(method); flg.set(o == null); return o; } if (wasNull.equals(method)) { return flg.get(); } return null; } }; return (ResultSet) Proxy.newProxyInstance(Helper.class.getClassLoader(), new Class[] { ResultSet.class }, handler); }
/** * 通过此方法添加的监听将通过代理 调用前显示遮罩 * <p> */ public void initListSelectionListener() { InvocationHandler handler2 = new AnnotationInvocationHandler(this, this.getListSelectionListenerImpl()); ListSelectionListenerImpl cc = this.getListSelectionListenerImpl(); ListSelectionListener listener = (ListSelectionListener) Proxy.newProxyInstance(cc.getClass().getClassLoader(), cc.getClass().getInterfaces(), handler2); dbList.addListSelectionListener(listener); }
@SuppressWarnings("unchecked") private <T> T proxy(Class<T> interfc, InvocationHandler ih) { if (!interfc.isInterface()) { throw new IllegalArgumentException("only proxying interfaces: " + interfc); } return (T)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{ interfc }, ih); }
/** * Generate proxy object array of the given size. */ Proxy[] genProxies(int size) throws Exception { Class proxyClass = Proxy.getProxyClass(DummyInterface.class.getClassLoader(), new Class[] { DummyInterface.class }); Constructor proxyCons = proxyClass.getConstructor(new Class[] { InvocationHandler.class }); Object[] consArgs = new Object[] { new DummyHandler() }; Proxy[] proxies = new Proxy[size]; for (int i = 0; i < size; i++) proxies[i] = (Proxy) proxyCons.newInstance(consArgs); return proxies; }
public InvocationHandler getInvocationHandler() { final DynamicStub stub = new DynamicStubImpl( classData.getTypeIds() ) ; return getInvocationHandler( stub ) ; }
protected Constructor<?> getResultSetConstructor() throws NoSuchMethodException { if (resultSetConstructor == null) { Class<?> proxyClass = Proxy.getProxyClass(StatementDecoratorInterceptor.class.getClassLoader(), new Class[] { ResultSet.class }); resultSetConstructor = proxyClass.getConstructor(new Class[] { InvocationHandler.class }); } return resultSetConstructor; }
private Object createChangeListener(Class<?> clazz) { return Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{clazz}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { changed(); return null; } }); }
@SuppressLint("PrivateApi") private static void installCondomProcessActivityManager(final CondomCore condom) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { final Class<?> ActivityManagerNative = Class.forName("android.app.ActivityManagerNative"); Field ActivityManagerNative_gDefault = null; if (SDK_INT <= N_MR1) try { ActivityManagerNative_gDefault = ActivityManagerNative.getDeclaredField("gDefault"); } catch (final NoSuchFieldException ignored) {} // ActivityManagerNative.gDefault is no longer available on Android O. if (ActivityManagerNative_gDefault == null) { ActivityManagerNative_gDefault = ActivityManager.class.getDeclaredField("IActivityManagerSingleton"); } ActivityManagerNative_gDefault.setAccessible(true); final Class<?> Singleton = Class.forName("android.util.Singleton"); final Method Singleton_get = Singleton.getDeclaredMethod("get"); Singleton_get.setAccessible(true); final Field Singleton_mInstance = Singleton.getDeclaredField("mInstance"); Singleton_mInstance.setAccessible(true); final Class<?> IActivityManager = Class.forName("android.app.IActivityManager"); final Object/* Singleton */singleton = ActivityManagerNative_gDefault.get(null); if (singleton == null) throw new IllegalStateException("ActivityManagerNative.gDefault is null"); final Object/* IActivityManager */am = Singleton_get.invoke(singleton); if (am == null) throw new IllegalStateException("ActivityManagerNative.gDefault.get() returns null"); final InvocationHandler handler; if (Proxy.isProxyClass(am.getClass()) && (handler = Proxy.getInvocationHandler(am)) instanceof CondomProcessActivityManager) { Log.w(TAG, "CondomActivityManager was already installed in this process."); ((CondomProcessActivityManager) handler).mCondom = condom; } else { final Object condom_am = Proxy.newProxyInstance(condom.mBase.getClassLoader(), new Class[] { IActivityManager }, new CondomProcessActivityManager(condom, am)); Singleton_mInstance.set(singleton, condom_am); } }
/** * 创建一个动态代理根据传入的类型. 如果我们正在维护的是一个Map,那么当调用出现异常时我们将从Map中取值. * * @param proxyType 需要动态代理的类型 * @return 动态代理生成的对象 */ @SuppressWarnings("unchecked") public <P> P as(Class<P> proxyType) { final boolean isMap = (object instanceof Map); final InvocationHandler handler = new InvocationHandler() { @Mark public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); try { return on(object).call(name, args).get(); } catch (ReflectException e) { if (isMap) { Map<String, Object> map = (Map<String, Object>) object; int length = (args == null ? 0 : args.length); if (length == 0 && name.startsWith("get")) { return map.get(property(name.substring(3))); } else if (length == 0 && name.startsWith("is")) { return map.get(property(name.substring(2))); } else if (length == 1 && name.startsWith("set")) { map.put(property(name.substring(3)), args[0]); return null; } } throw e; } } }; return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[]{proxyType}, handler); }