动态代理实现

匿名 (未验证) 提交于 2019-12-03 00:29:01
package com.work3.staticaop;  import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy;  interface Subject { 	void action(); }  class RealSubject implements Subject { 	@Override 	public void action() { 		System.out.println("这是被代理类"); 	} }  class DynomicProxyHandler implements InvocationHandler{  	Object obj; 	 	/** 	 * 返回一个代理传入参数类型的对象 	 * @param obj 	 * @return 	 */ 	public Object blind(Object obj) { 		this.obj = obj; 		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this); 	} 	 	/** 	 * 反射调用方法 	 */ 	@Override 	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 		return method.invoke(obj, args); 	} 	 	@SuppressWarnings("unchecked") 	public static <T> T proxyHandler(T t) { 		DynomicProxyHandler mih = new DynomicProxyHandler(); 		return (T) mih.blind(t); 	} 	 }  public class DynomicProxy {  	public static void main(String[] args) { 		Subject subject = DynomicProxyHandler.proxyHandler(new RealSubject()); 		subject.action(); 		 		ClothFactory cf = DynomicProxyHandler.proxyHandler(new NikeClothFactory()); 		cf.productCloth(); 	} } 

文章来源: 动态代理实现
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!