java动态代理

来源:互联网 发布:蜂窝移动网络 4g 编辑:程序博客网 时间:2024/06/06 02:41

使用java提供的Proxy类和InvocationHandler实现动态代理类:

接口

public interface IRequest {public boolean revokeRequest(boolean isHavePermission);}

接口的实现类:

public class RequestImpl implements IRequest {@Overridepublic boolean revokeRequest(boolean isHavePermission) {System.out.println("revokeRequest 用户是否有权限" + isHavePermission);return isHavePermission;}}

使用proxy动态产生被代理的对象,也就是RequestImpl:

public class RequestProxy implements InvocationHandler {private Object target; // 目标对象public Object bind(Object target) {this.target = target;Class<?> cl = target.getClass();return Proxy.newProxyInstance(cl.getClassLoader(), cl.getInterfaces(), this);}/* * 工厂方法,产生被代理的对象 * */public Object factory(Object target) {this.target = target;Class<?> cl = target.getClass();return Proxy.newProxyInstance(cl.getClassLoader(), cl.getInterfaces(), this);}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {Object result = null;System.out.println("调用方法前的操作...");result = method.invoke(target, args);System.out.println("调用方法后的操作...");return result;}}

用户程序的使用:


public class MainClass {public static void main(String[] args) {RequestProxy proxy = new RequestProxy();IRequest request = (IRequest) proxy.factory(new RequestImpl());boolean result = request.revokeRequest(true);System.out.println(result);}}


0 0
原创粉丝点击