@Override public Object createProxy(Interceptor interceptor, Class<?>[] types, MethodPointcut methodPointcut) { ProxyType proxyType = evalProxyType(types); Enhancer eh = new Enhancer(); DefaultMethodInterceptor dmi = new DefaultMethodInterceptor(interceptor); DefaultDispatcher dispatcher = new DefaultDispatcher(interceptor.getTarget()); Callback[] callbacks = new Callback[] { dmi, dispatcher }; eh.setCallbacks(callbacks); CallbackFilter cf = new CallbackFilterAdapter(methodPointcut); eh.setCallbackFilter(cf); switch (proxyType) { case CLASS: Class<?> clazz = types[0]; eh.setSuperclass(clazz); return eh.create(); case INTERFACES: eh.setInterfaces(types); return eh.create(); } throw new UnsupportedOperationException("Unsupported proxy types!"); }
private static Object newProxyByCglib(Typing typing, Handler handler) { Enhancer enhancer = new Enhancer() { /** includes all constructors */ protected void filterConstructors(Class sc, List constructors) {} }; enhancer.setClassLoader(Thread.currentThread().getContextClassLoader()); enhancer.setUseFactory(true); enhancer.setSuperclass(typing.superclass); enhancer.setInterfaces(typing.interfaces.toArray(new Class[0])); enhancer.setCallbackTypes(new Class[] { MethodInterceptor.class, NoOp.class }); enhancer.setCallbackFilter(new CallbackFilter() { /** ignores bridge methods */ public int accept(Method method) { return method.isBridge() ? 1 : 0; } }); Class<?> proxyClass = enhancer.createClass(); Factory proxy = (Factory) new ObjenesisStd().newInstance(proxyClass); proxy.setCallbacks(new Callback[] { asMethodInterceptor(handler), new SerializableNoOp() }); return proxy; }
/** * 代理某一个对象指定方法,并在这个方法执行前后加入新方法,可指定过滤掉非代理的方法 * @author nan.li * @param t * @param before 执行目标方法前要执行的方法 * @param after 执行目标方法后要执行的方法 * @return */ @SuppressWarnings("unchecked") public static <T> T proxySurround(T t, CustomMethod before, CustomMethod after, CallbackFilter callbackFilter) { MethodInterceptor methodInterceptor = new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { before.execute(obj, method, args); Object result = null; try { result = proxy.invokeSuper(obj, args); } finally { after.execute(obj, method, args); } return result; } }; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(t.getClass()); // 回调方法 // enhancer.setCallback(methodInterceptor); enhancer.setCallbacks(new Callback[] {methodInterceptor, NoOp.INSTANCE}); //NoOp回调把对方法的调用直接委派到这个方法在父类中的实现。 //Methods using this Enhancer callback ( NoOp.INSTANCE ) will delegate directly to the default (super) implementation in the base class. //setCallbacks中定义了所使用的拦截器,其中NoOp.INSTANCE是CGlib所提供的实际是一个没有任何操作的拦截器, 他们是有序的。一定要和CallbackFilter里面的顺序一致。 enhancer.setCallbackFilter(callbackFilter); // 创建代理对象 return (T)enhancer.create(); }
public void testSupportProxiesUsingFactoryWithMultipleCallbacks() throws NullPointerException { final Enhancer enhancer = new Enhancer(); enhancer.setCallbacks(new Callback[]{ new DelegatingInterceptor(null), new DelegatingHandler(null), new DelegatingDispatcher(null), NoOp.INSTANCE}); enhancer.setCallbackFilter(new CallbackFilter() { int i = 1; public int accept(Method method) { if (method.getDeclaringClass() == Runnable.class) { return 0; } return i < 3 ? i++ : i; } }); enhancer.setInterfaces(new Class[]{Runnable.class}); enhancer.setUseFactory(true); final Runnable orig = (Runnable)enhancer.create(); final String xml = xstream.toXML(orig); final Factory deserialized = (Factory)xstream.fromXML(xml); assertTrue("Not a Runnable anymore", deserialized instanceof Runnable); Callback[] callbacks = deserialized.getCallbacks(); assertEquals(4, callbacks.length); assertTrue(callbacks[0] instanceof DelegatingInterceptor); assertTrue(callbacks[1] instanceof DelegatingHandler); assertTrue(callbacks[2] instanceof DelegatingDispatcher); assertTrue(callbacks[3] instanceof NoOp); }
public void testThrowsExceptionForProxiesNotUsingFactoryWithMultipleCallbacks() throws NullPointerException { final Enhancer enhancer = new Enhancer(); enhancer.setCallbacks(new Callback[]{ new DelegatingInterceptor(null), new DelegatingHandler(null), new DelegatingDispatcher(null), NoOp.INSTANCE}); enhancer.setCallbackFilter(new CallbackFilter() { int i = 1; public int accept(Method method) { if (method.getDeclaringClass() == Runnable.class) { return 0; } return i < 3 ? i++ : i; } }); enhancer.setInterfaces(new Class[]{Runnable.class}); enhancer.setUseFactory(false); final Runnable orig = (Runnable)enhancer.create(); try { xstream.toXML(orig); fail("Thrown " + ConversionException.class.getName() + " expected"); } catch (final ConversionException e) { } }
@Override public <T> T createProxy(Class<T> localizable, LocalizationProvider localizationProvider) { Method[] methods = localizable.getDeclaredMethods(); List<Callback> callbacks = new ArrayList<Callback>(methods.length + 1); final Map<Method, Integer> method2CallbackIndex = new HashMap<Method, Integer>(methods.length); callbacks.add(NoOp.INSTANCE); for (Method localizableMethod : methods) { callbacks.add(createCallback(localizationProvider, localizableMethod)); method2CallbackIndex.put(localizableMethod, callbacks.size() - 1); } CallbackFilter callbackFilter = new CallbackFilter() { @Override public int accept(Method method) { Integer index = method2CallbackIndex.get(method); return index == null ? 0 : index; } }; Enhancer enhancer = new Enhancer(); enhancer.setInterfaces(new Class[]{localizable}); enhancer.setCallbackFilter(callbackFilter); enhancer.setCallbacks(callbacks.toArray(new Callback[callbacks.size()])); enhancer.setUseFactory(false); @SuppressWarnings("unchecked") T instance = (T) enhancer.create(); return instance; }
/** * 代理一个对象<br> * 仅代理其列出的几个方法 * @author Administrator * @param t * @param before * @param after * @param methodNames * @return */ @SuppressWarnings("unchecked") public static <T> T proxySurroundIncludes(T t, CustomMethod before, CustomMethod after, String... methodNames) { MethodInterceptor methodInterceptor = new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { before.execute(obj, method, args); Object result = null; try { result = proxy.invokeSuper(obj, args); } finally { after.execute(obj, method, args); } return result; } }; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(t.getClass()); enhancer.setCallbacks(new Callback[] {methodInterceptor, NoOp.INSTANCE}); enhancer.setCallbackFilter(new CallbackFilter() { @Override public int accept(Method paramMethod) { //仅判断代理的情况 String name = paramMethod.getName(); if (ArrayUtils.contains(methodNames, name)) { return ProxyFlag.DO_PROXY.get(); } //默认不代理 return ProxyFlag.DO_NOT_PROXY.get(); } }); // 创建代理对象 return (T)enhancer.create(); }
/** * 代理一个对象<br> * 过滤掉几个不想代理的方法 * @author Administrator * @param t * @param before * @param after * @param methodNames * @return */ @SuppressWarnings("unchecked") public static <T> T proxySurroundExcludes(T t, CustomMethod before, CustomMethod after, String... methodNames) { MethodInterceptor methodInterceptor = new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { before.execute(obj, method, args); Object result = null; try { result = proxy.invokeSuper(obj, args); } finally { after.execute(obj, method, args); } return result; } }; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(t.getClass()); enhancer.setCallbacks(new Callback[] {methodInterceptor, NoOp.INSTANCE});//设置多个代理对象。NoOp.INSTANCE是一个空代理 enhancer.setCallbackFilter(new CallbackFilter() { @Override public int accept(Method paramMethod) { //CallbackFilter可以实现不同的方法使用不同的回调方法。所以CallbackFilter称为"回调选择器"更合适一些。 //CallbackFilter中的accept方法,根据不同的method返回不同的值i,这个值是在callbacks中callback对象的序号,就是调用了callbacks[i]。 String name = paramMethod.getName(); if (ArrayUtils.contains(methodNames, name)) { return ProxyFlag.DO_NOT_PROXY.get(); } return ProxyFlag.DO_PROXY.get(); } }); // 创建代理对象 return (T)enhancer.create(); }
@SuppressWarnings("unchecked") public static <T> T proxyByPrivilegeIncludes(T t, CustomMethodWithRet checkPrivilege, String... methodNames) { MethodInterceptor methodInterceptor = new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { boolean checkResult = checkPrivilege.execute(obj, method, args);//权限验证的结果 if (checkResult) { //验证通过,才执行这个方法 Object result = null; result = proxy.invokeSuper(obj, args); return result; } else { return null; } } }; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(t.getClass()); enhancer.setCallbacks(new Callback[] {methodInterceptor, NoOp.INSTANCE}); enhancer.setCallbackFilter(new CallbackFilter() { @Override public int accept(Method paramMethod) { //仅判断代理的情况 String name = paramMethod.getName(); if (ArrayUtils.contains(methodNames, name)) { return ProxyFlag.DO_PROXY.get(); } //默认不代理 return ProxyFlag.DO_NOT_PROXY.get(); } }); // 创建代理对象 return (T)enhancer.create(); }
@SuppressWarnings("unchecked") public static <T> T proxyByPrivilegeExcludes(T t, CustomMethodWithRet checkPrivilege, String... methodNames) { MethodInterceptor methodInterceptor = new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { boolean checkResult = checkPrivilege.execute(obj, method, args);//权限验证的结果 if (checkResult) { //验证通过,才执行这个方法 Object result = null; result = proxy.invokeSuper(obj, args); return result; } else { return null; } } }; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(t.getClass()); enhancer.setCallbacks(new Callback[] {methodInterceptor, NoOp.INSTANCE}); enhancer.setCallbackFilter(new CallbackFilter() { @Override public int accept(Method paramMethod) { //仅判断代理的情况 String name = paramMethod.getName(); if (ArrayUtils.contains(methodNames, name)) { return ProxyFlag.DO_NOT_PROXY.get(); } //默认不代理 return ProxyFlag.DO_PROXY.get(); } }); // 创建代理对象 return (T)enhancer.create(); }
private CallbackFilter getCallbackFilter() { return _callbackFilter; }
@Override public Object createProxy(ClassLoader cl, Class<?>[] types, InvocationHandler hdlr) { // Enhancers are used to generate new classes at runtime // using an interface or class as a template. Enhancer enhancer = new Enhancer(); Class<?> sup = getSuperClass(types); List<Class<?>> inflist = getInterfaces(types); inflist.add(HandledProxy.class); Class<?>[] infs = inflist.toArray(new Class[0]); // We tell the Enhancer what we want the super class of the // dynamically generated class to be. If no class is specified, // java.lang.Object will be the super class. if(sup != null){enhancer.setSuperclass(sup);} // We tell the Enhancer the interfaces that the new class should // implement. enhancer.setInterfaces(infs); // We create our MethodInterceptor that is going to be called whenever // anyone invokes a method on an instance of our dynamically genereated // class. CglibProxy intercept = new CglibProxy(hdlr); // Each dynamically generated class has one or more MethodInterceptors (Callbacks) // that can be registered to handle different method calls. In this case, we // add two MethodInterceptors. One interceptor deals with calls to our secret // method to get the InvocationHandler for a proxy. The second MethodInterceptor // delegates all other calls to the InvocationHandler that the caller specified // when they created the proxy. For this exercise, the InvocationHandler is always // going to be an instance of Mock. enhancer.setCallbackTypes(new Class[] { HandledProxyInterceptor.class, intercept.getClass() }); // Since we are injecting multiple MethodInterceptors, we have to tell the // generated class which one to use for which method call. enhancer.setCallbackFilter(new CallbackFilter() { @Override public int accept(Method arg0) { return (arg0.getName() .equals(NON_CLASHING_ID_METHOD_NAME)) ? 0 : 1; } }); // We ask the Enhancer to generate the bytecode for the new class // and load it into the JVM as a new Class object. final Class<?> proxyClass = enhancer.createClass(); Enhancer.registerCallbacks(proxyClass, new Callback[] { new HandledProxyInterceptor(hdlr), intercept }); Object proxy = null; try{ proxy = proxyClass.newInstance(); } catch(Exception e){ throw new RuntimeException(e); } return proxy; }