当前位置: 代码迷 >> J2EE >> 动态代理工厂类,该怎么解决
  详细解决方案

动态代理工厂类,该怎么解决

热度:30   发布时间:2016-04-22 01:44:34.0
动态代理工厂类
Java code
import java.lang.reflect.InvocationHandler;  import java.lang.reflect.Proxy;  public abstract class JdkProxyFactoryUtils {        public static Object wrap(InvocationHandlerWrapper hander) {      Class<?> clazz = hander.getBean().getClass();      return Proxy.newProxyInstance(clazz.getClassLoader(),          clazz.getInterfaces(), hander);      }  } 


Java code
import java.lang.reflect.InvocationHandler;  import java.lang.reflect.Method;    public abstract class InvocationHandlerWrapper implements InvocationHandler {      private Object object = null;        public InvocationHandlerWrapper(Object object) {      super();      this.object = object;      }        public Object getBean() {      return object;      }        abstract public Object invoke(Object proxy, Method method, Object[] args)          throws Throwable;    }  

测试代码,定义一个过滤器,对HttpServletRequest和HttpServletResponse包装,实现输出调用的方法的名称。
Java code
package com.mvc.filter;import java.io.IOException;import java.lang.reflect.Method;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.mvc.common.InvocationHandlerWrapper;import com.mvc.common.JdkProxyFactoryUtils;public class ProxyFilter implements Filter {    @Override    public void destroy() {    }    @Override    public void doFilter(ServletRequest request, ServletResponse response,        FilterChain chain) throws IOException, ServletException {    HttpServletRequest req = (HttpServletRequest) request;    HttpServletResponse resp = (HttpServletResponse) response;    HttpServletRequest httpServletRequestWrapper = (HttpServletRequest) JdkProxyFactoryUtils        .wrap(new InvocationHandlerWrapper(req) {            @Override            public Object invoke(Object proxy, Method method,                Object[] args) throws Throwable {            Object result = method.invoke(this.getBean(), args);            System.out.println(method.getName());            return result;            }        });    HttpServletResponse httpServletResponseWrapper = (HttpServletResponse) JdkProxyFactoryUtils        .wrap(new InvocationHandlerWrapper(resp) {            @Override            public Object invoke(Object proxy, Method method,                Object[] args) throws Throwable {            Object result = method.invoke(this.getBean(), args);            System.out.println(method.getName());            return result;            }        });    chain.doFilter(httpServletRequestWrapper, httpServletResponseWrapper);    }    @Override    public void init(FilterConfig arg0) throws ServletException {    }}



------解决方案--------------------
  相关解决方案