@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { if (args == null || args.length > 1 || args.length == 0) { return methodProxy.invokeSuper(obj, args); } if (method.getName().contains("guiRender") || method.getName().contains("mouseClick")) { Object arg0 = args[0]; if (arg0 instanceof GuiScreenEvent) { GuiScreenEvent drawEvent = (GuiScreenEvent) arg0; if (drawEvent.getGui() instanceof GuiMainMenu) { // Don't invoke. return methodProxy.getSignature().getReturnType().getOpcode(VOID); } } } return methodProxy.invokeSuper(obj, args); }
@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { // Give our delegate a chance to intercept, and cache the decision if(delegatedMethods.get(method, () -> method.getDeclaringClass() != Object.class && Methods.hasOverrideIn(Delegate.class, method))) { return method.invoke(delegate, args); } // If we have a value for the property, return that final Object value = values.get(method); if(value != null) return value; // If there's no value, then the method MUST be callable (or the code is broken). // This can only fail for an abstract non-property method (which we should probably be checking for). if(method.isDefault()) { // invokeSuper doesn't understand default methods return defaultMethodHandles.get(method) .bindTo(obj) .invokeWithArguments(args); } else { return proxy.invokeSuper(obj, args); } }
@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if(isDecorated(method)) { // Decorated method return proxy.invokeSuper(obj, args); } else { final T t = ((Decorator<T>) obj).delegate(); if(method.getDeclaringClass().isInstance(t)) { // Forwarded method return proxy.invoke(t, args); } else { // Forwarded method shadowed by an interface method in the decorator. // // This can happen if the decorator implements an interface that the // base class doesn't, and that interface contains a method that shadows // one on the base class. Java would allow the method to be called on the // base anyway, but MethodProxy refuses to invoke it on something that // is not assignable to the method's declaring type. So, unfortunately, // we have to fall back to the JDK to handle this case. return methodHandles.get(method, () -> resolver.virtualHandle(t.getClass(), method).bindTo(t) ).invokeWithArguments(args); } } }
/** * 实现MethodInterceptor接口要重写的方法。 * 回调方法 */ public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { Class[] paramTypes = method.getParameterTypes(); // 找到realObject对象中,一模一样的方法 Method method2 = ReflectUtils.findMethod(shadowObject.getClass(), method.getName(), paramTypes); if (method2 == null) { throw new RuntimeException("method \'" + shadowObject.getClass() + "." + method.getName() + "\' not found."); } try { return method2.invoke(shadowObject, args); } catch (InvocationTargetException e) { Throwable targetEx = e.getTargetException(); throw targetEx; } }
private Object invoke(MethodProxy proxy, Object[] arguments, Class<?> declaredReturnType) throws Throwable { requests.increment(); //noinspection unused try (TimerContext timer = TimerContext.timerMillis(totalRequestTime::add)) { UUID requestID = UUID.randomUUID(); ServiceRequestMessage msg = ServiceRequestMessage.builder() .setRequestID(requestID.toString()) .setServiceName(proxyInterface.getName()) .setMethodName(proxy.getSignature().getName()) .setArgumentTypes(fromTypes(proxy.getSignature().getArgumentTypes())) .setArguments(arguments) .build(); if (LOGGER.isDebug()) LOGGER.debug("Signalling request"); RequestHandler handler = RequestHandler.signal(requestSink, msg, true, maxWait); return handleResponses(handler, declaredReturnType); } }
public Object intercept( final Object obj, final Method method, final Object[] args, final MethodProxy proxy) throws Throwable { if (constructed) { Object result = invoke(method, args, obj); if (result==INVOKE_IMPLEMENTATION) { return proxy.invoke( getImplementation(), args ); } else { return result; } } else { //while constructor is running return proxy.invokeSuper(obj, args); } }
/** * 拦截所有调用,选择正确的实例执行命令 * @param o 调用实例 * @param method 调用方法 * @param args 方法参数 * @param methodProxy 方法代理 * @return 命令返回值 * @throws Throwable 方法执行异常或连接异常 */ @Override public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { GedisInstanceType type; if (READ_METHOD_LIST.contains(method.getName())) { type = GedisInstanceType.READ; } else { type = GedisInstanceType.WRITE; } JedisPool pool = getJedisPoolByType(type); Jedis jedis = pool.getResource(); try { return method.invoke(jedis, args); } catch (Exception e) { jedis.close(); throw e; } finally { jedis.close(); } }
public Object intercept(final Object obj, final Method method, final Object[] args, final MethodProxy proxy) throws Throwable { if (shouldSkip(method)) { return null; } Object result; if (baseClassMethod(method, obj.getClass())) { result = runBaseObjectMethod(obj, method, args, proxy); } else if (isParameterConverter(method)) { result = runBaseObjectMethod(obj, method, args, proxy); } else { result = testStepResult(obj, method, args, proxy); } return result; }
private Object testStepResult(final Object obj, final Method method, final Object[] args, final MethodProxy proxy) throws Throwable { if (!isATestStep(method)) { return runNormalMethod(obj, method, args, proxy); } if (shouldSkip(method)) { notifySkippedStepStarted(method, args); return skipTestStep(obj, method, args, proxy); } else { notifyStepStarted(method, args); return runTestStep(obj, method, args, proxy); } }
private Object runTestStep(final Object obj, final Method method, final Object[] args, final MethodProxy proxy) throws Throwable { LOGGER.debug("STARTING STEP: {}", method.getName()); Object result = null; try { result = executeTestStepMethod(obj, method, args, proxy, result); LOGGER.debug("STEP DONE: {}", method.getName()); } catch (AssertionError failedAssertion) { error = failedAssertion; logStepFailure(method, args, failedAssertion); return appropriateReturnObject(obj, method); } catch (AssumptionViolatedException assumptionFailed) { return appropriateReturnObject(obj, method); } catch (Throwable testErrorException) { error = testErrorException; logStepFailure(method, args, forError(error).convertToAssertion()); return appropriateReturnObject(obj, method); } return result; }
private Object executeTestStepMethod(Object obj, Method method, Object[] args, MethodProxy proxy, Object result) throws Throwable { try { result = invokeMethod(obj, args, proxy); notifyStepFinishedFor(method, args); } catch (PendingStepException pendingStep) { notifyStepPending(pendingStep.getMessage()); } catch (IgnoredStepException ignoredStep) { notifyStepIgnored(ignoredStep.getMessage()); } catch (AssumptionViolatedException assumptionViolated) { notifyAssumptionViolated(assumptionViolated.getMessage()); } Preconditions.checkArgument(true); return result; }
@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { // 排除Object类中的toString等方法 boolean objFlag = method.getDeclaringClass().getName().equals("java.lang.Object"); if (!objFlag) { System.out.println("before"); } Object result = null; // 我们一般使用proxy.invokeSuper(obj,args)方法。这个很好理解,就是执行原始类的方法。还有一个方法proxy.invoke(obj,args),这是执行生成子类的方法。 // 如果传入的obj就是子类的话,会发生内存溢出,因为子类的方法不挺地进入intercept方法,而这个方法又去调用子类的方法,两个方法直接循环调用了。 result = methodProxy.invokeSuper(obj, args); // result = methodProxy.invoke(obj, args); if (!objFlag) { System.out.println("after"); } return result; }
public static void main(String[] args) { while(true) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(ClassPermGenOOM.class); enhancer.setUseCache(Boolean.FALSE); enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable { return arg3.invokeSuper(arg0, arg2); } }); enhancer.create(); } }
public static void main(String[] args) { Tmp tmp = new Tmp(); while (!Thread.interrupted()) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Tmp.class); enhancer.setUseCache(false); enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable { return arg3.invokeSuper(arg0, arg2); } }); enhancer.create(); } System.out.println(tmp.hashCode()); }
@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { boolean shouldProxy = method.isAnnotationPresent(Transactional.class); if (shouldProxy) { Connection conn = dataSource.getConnection(); conn.setAutoCommit(false); Object result; try { result = methodProxy.invokeSuper(obj, args); conn.commit(); return result; } catch (Exception e) { conn.rollback(); throw e; } } return methodProxy.invokeSuper(obj, args); }
@SuppressWarnings("unchecked") public T decode(final BitBuffer buffer, final Resolver resolver, final Builder builder) throws DecodingException { final int size = wrapped.getSize().eval(resolver); final long pos = buffer.getBitPos(); ClassLoader loader = this.getClass().getClassLoader(); Enhancer enhancer = new Enhancer(); enhancer.setClassLoader(loader); enhancer.setSuperclass(type); enhancer.setCallback(new MethodInterceptor() { private Object actual; public Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (actual == null) { buffer.setBitPos(pos); actual = wrapped.decode(buffer, resolver, builder); } return proxy.invoke(actual, args); } }); buffer.setBitPos(pos + size); return (T) enhancer.create(); }
@Override public Object intercept(Object objectModel, Method method, Object[] params, MethodProxy methodProxy) throws Throwable { if (conditionalSet.getExpression() instanceof BooleanExpression) { if (((BooleanExpression)conditionalSet.getExpression()).getMakeSet()) { ReflectionUtils.invokeMethod(method, conditionalSet.getTarget(), params); } } else { ContainsExpression expression = (ContainsExpression) conditionalSet.getExpression(); String fieldName = getFieldByGetOrSet(method); if (!expression.isEmpty() && expression.getFields().contains(fieldName)) { ReflectionUtils.invokeMethod(method, conditionalSet.getTarget(), params); } } return null; }
/** * Intercepts the method call by wrapping the invocation in a {@link CglibProxyInvocation} and delegating the * handling to the invocation handler. * * @param proxy The proxy, not null * @param method The method that was called, not null * @param arguments The arguments that were used, not null * @param methodProxy The cglib method proxy, not null * @return The value to return for the method call, ignored for void methods */ public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { if (isFinalizeMethod(method)) { return null; } else if (isEqualsMethod(method)) { return proxy == arguments[0]; } else if (isHashCodeMethod(method)) { return super.hashCode(); } else if (isCloneMethod(method)) { return proxy; } else if (isToStringMethod(method)) { return getProxiedType().getSimpleName() + "@" + Integer.toHexString(super.hashCode()); } ProxyInvocation invocation = new CglibProxyInvocation(mockName, method, asList(arguments), getProxiedMethodStackTrace(), proxy, methodProxy); return invocationHandler.handleInvocation(invocation); }
@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { String methodName = method.getName(); if("close".equals(methodName)) { jedisSessionTimer.update(System.nanoTime()-start, TimeUnit.NANOSECONDS); return method.invoke(jedis, args); } else if(jedisMethods.contains(methodName)) { long methodStart=System.nanoTime(); Object returnValue = method.invoke(jedis, args); timerMap.get(methodName).update(System.nanoTime()-methodStart, TimeUnit.NANOSECONDS);; return returnValue; } else { return method.invoke(jedis, args); } }
@Override public Object intercept(final Object proxy, final Method method, final Object[] args, final MethodProxy methodProxy) throws Throwable { final FeatureResolver resolver = FeatureResolver.newFeatureResolver(delegate.getClass()).withTestMethod(method) .withDefaultCleanupPhase(CleanupPhase.NONE).build(); Object result = null; final TestMethodInvocationImpl invocation = new TestMethodInvocationImpl(delegate, method, resolver); executor.processBefore(invocation); try { result = methodProxy.invoke(delegate, args); } catch (final Exception e) { invocation.setTestException(e); executor.processAfter(invocation); throw e; } executor.processAfter(invocation); return result; }
@Override public Object intercept(final Object proxy, final Method method, final Object[] args, final MethodProxy methodProxy) throws Throwable { final Object other = args[0]; if (proxy == other) { return true; } else if (other instanceof Factory) { for (final Callback callback : ((Factory) other).getCallbacks()) { if (callback.getClass().isAssignableFrom(EqualsInterceptor.class)) { return target.equals(((EqualsInterceptor) callback).target); } } } return target.equals(other); }
@Override public Object intercept(final Object proxy, final Method method, final Object[] args, final MethodProxy methodProxy) throws Throwable { if (isObjectMethod(method) || hasConcordionAnnotations(method)) { return methodProxy.invoke(delegate, args); } final FeatureResolver resolver = FeatureResolver.newFeatureResolver(delegate.getClass()).withTestMethod(method) .withDefaultCleanupPhase(CleanupPhase.NONE).build(); Object result = null; final TestInvocationImpl invocation = new TestInvocationImpl(delegate, method, resolver); executor.processBefore(invocation); try { result = methodProxy.invoke(delegate, args); } catch (final Exception e) { invocation.setTestException(e); executor.processAfter(invocation); throw e; } executor.processAfter(invocation); return result; }
@SuppressWarnings("unchecked") public T bind() { if (__bound == null) { __bound = (T) ClassUtils.wrapper(__source).duplicate(Enhancer.create(__targetClass, new MethodInterceptor() { public Object intercept(Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy) throws Throwable { Object _result = methodProxy.invokeSuper(targetObject, methodParams); PropertyStateMeta _meta = __propertyStates.get(targetMethod.getName()); if (_meta != null && ArrayUtils.isNotEmpty(methodParams) && !ObjectUtils.equals(_meta.getOriginalValue(), methodParams[0])) { _meta.setNewValue(methodParams[0]); } return _result; } })); } return __bound; }
/** * @see net.sf.cglib.proxy.MethodInterceptor#intercept(Object, * Method, Object[], net.sf.cglib.proxy.MethodProxy) */ @Override public Object intercept(final Object object, final Method method, final Object[] args, final MethodProxy proxy) throws Throwable { if (isFinalizeMethod(method)) { // swallow finalize call return null; } else if (isEqualsMethod(method)) { return (equals(args[0])) ? Boolean.TRUE : Boolean.FALSE; } else if (isHashCodeMethod(method)) { return hashCode(); } else if (isToStringMethod(method)) { return toString(); } else if (isWriteReplaceMethod(method)) { return writeReplace(); } else if (method.getDeclaringClass().equals(ILazyInitProxy.class)) { return getObjectLocator(); } if (target == null) { target = locator.locateProxyTarget(); } return proxy.invoke(target, args); }
@Override public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { /** * ����������� */ Object result = null; methodBefore(proxy,args); // System.out.println("���↑ʼ"); // ͨ����������ø����еķ��� result = methodProxy.invokeSuper(proxy, args); methodAfter(result); // System.out.println("�������"); // // �Խ�������˸��� ����ţ������� // result = "2"; return result; }
@Override public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { String methodName = method.getName(); if (args.length == 1 && methodName.startsWith("set") && methodName.length() >= 4 && method.getReturnType() == void.class) { String property = methodName.substring(3); Object newValue = args[0]; Object prevValue = ReflectionUtils.callGetter(object, (newValue instanceof Boolean ? "is" : "get") + property); ValueChange change = values.get(property); if (change != null) { change.newValue = newValue; } else { if (prevValue == null && newValue != null || prevValue != null && newValue == null || prevValue != null && !prevValue.equals(newValue)) { change = new ValueChange(ReflectionUtils.callGetter(object, (newValue instanceof Boolean ? "is" : "get") + property), newValue); values.put(property, change); } } methodProxy.invoke(object, args); return null; } else if (args.length == 0 && (methodName.startsWith("get") || methodName.startsWith("is"))) { return methodProxy.invoke(object, args); } else { throw new RuntimeException("Can't intercept bean change due to unknown method call: " + method.getName() + " on " + o.getClass().getName()); } }
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { String property = ReflectionUtils.getPropertyFromSetter(method); if (property != null) { Method getter; try { getter = ReflectionUtils.getGetterFromProperty(obj.getClass(), property); } catch (NoSuchMethodException e) { throw new RuntimeException("A probable bug in the Currency Cloud SDK: no getter found for setter " + method, e); } Object prevPropertyValue = getter.invoke(obj); Object newPropertyValue = args[0]; if (!Objects.equals(prevPropertyValue, newPropertyValue)) { dirtyProperties.put(property, newPropertyValue); } } return method.invoke(watched, args); }
@Override public Object intercept(Object target, Method targetMethod, Object[] params,MethodProxy methodProxy) throws Throwable { //当出现一个动态调用的时候,判断当前方法是不是接口中的方法,如果不是接口方法,直接使用原始的调用 //当spring在初始化的时候,会调用类型equals,hashCode等方法 if (!Modifier.isAbstract(targetMethod.getModifiers())) { return methodProxy.invokeSuper(target, params); } try{ return processor.process(targetMethod, params); }catch(Exception e){ logger.error("httpService access error " , e); } return null; }
@SuppressWarnings("unchecked") @Override public Object intercept(final Object proxy, final Method method, final Object[] args, final MethodProxy methodProxy) throws Throwable { @SuppressWarnings("rawtypes") final MethodListener methodListener = mMethodListeners.get(method .getName()); if (methodListener == null) { return null; } LOGGER.debug("invoke: {}", methodListener.getMethodName()); // FIXME: methodListener.invoke(args[0]); return null; }
/** * ���������� */ public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { try { Query qy = (Query)method.getAnnotation(Query.class); if (qy == null) { return proxy.invokeSuper(obj, args); } else { return this.QueryInterceptor(obj, method, args, proxy); } } catch (Exception e) { e.printStackTrace(); } return null; }
@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { Select query = method.getAnnotation(Select.class); Update update = method.getAnnotation(Update.class); if (query != null) { return this.AnnotationQueryIntercept(obj, method, args, methodProxy); } else if (update != null) { return this.AnnotationUpdateIntercept(obj, method, args, methodProxy); } else { return this.SqlMapIntercept(obj, method, args, methodProxy); } }
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if(args.length == 2){ String name = method.getName() ; if("invokeProxiedMethod".equals(name)){//pass the proxy MethodProxy mp = MethodProxy.find(obj.getClass(), ReflectUtils.getSignature((Member) args[0])) ; return mp.invokeSuper(obj, (Object[]) args[1]) ; } } String methodKey = this.getMethodKey(method) ; //call stub method Method stubMethod = this.stubMethods.get(methodKey) ; if(stubMethod != null){ return stubMethod.invoke(stub, args) ; } //call this RPCServiceImpl's method Method thisMethod = this.thisMethods.get(methodKey) ; if(thisMethod != null){ return thisMethod.invoke(this, args) ; } throw new NoSuchMethodException(methodKey) ; }
public void testMe(){ Article a = (Article) Enhancer.create(Article.class, new Class[]{DynamicUpdatable.class}, null, new Callback[]{ new MethodInterceptor(){ public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { proxy.invokeSuper(obj, args) ; System.out.println(method.getName()) ; return null; } } }) ; assertTrue(a instanceof DynamicUpdatable) ; a.getContent() ; }
@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (!aroundInvoked && Modifier.isPublic(method.getModifiers()) && !method.getDeclaringClass().equals(Object.class) && !"aroundSlimInvoke".equals(method.getName())) { aroundInvoked = true; try { return ((InteractionAwareFixture) obj).aroundSlimInvoke(interaction, method, args); } finally { aroundInvoked = false; } } else { return proxy.invokeSuper(obj, args); } }
@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { String methodName = method.getName(); if (methodName.startsWith("set") && args.length > 0) { handleSet(methodName, args); // Setters are fluent on record templates, so return "this" return obj; } else if (methodName.startsWith("get")) return handleGet(method); else if (methodName.startsWith("remove")) return handleRemove(methodName); return ObjectProxyHelper.handleObjectMethods(_clazz, obj, method, args); }
@SuppressWarnings({ "unchecked", "rawtypes" }) public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if(!method.isAnnotationPresent(Lazyload.class)){ return proxy.invokeSuper(obj, args); } Lazyload lazyload = method.getAnnotation(Lazyload.class); if(lazyload == null){ return proxy.invokeSuper(obj, args); } IEntityState iEntityState = (IEntityState)Enum.valueOf((Class)lazyload.enmuClass(), lazyload.state()); if(iEntityState == null){ return proxy.invokeSuper(obj, args); } if(obj instanceof Entity){ retrieve((Entity)obj,args,iEntityState); } return proxy.invokeSuper(obj, args); }
@Override protected void decorateInstance(T result, final MethodIntercept methodIntercept) { MethodInterceptor methodInterceptor = new MethodInterceptor() { public Object intercept(final Object proxy, Method method, Object[] args, final MethodProxy superProxy) throws Throwable { return methodIntercept.intercept(proxy, new MethodAdapter(method), args, new MethodIntercept.SuperInvoker() { public Object invokeSuper(Object[] superArgs) throws Throwable { return superProxy.invokeSuper(proxy, superArgs); } }); } }; Factory factory = (Factory) result; int callbackCount = factory.getCallbacks().length; for(int i = 0; i < callbackCount; i++) { factory.setCallback(i, methodInterceptor); } }
@Override @SuppressWarnings("unchecked") public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { MethodContext context = contexts.get(method); Object ret = context.hasDynamicLists() ? callEvalDynamicList(context, objects) : callEval(context, objects); if (ret == null) { return null; } if (contexts.get(method).getMapper() != null) { return contexts.get(method).getMapper().map(ret); } else { return ret; } }