动态代理

//业务类接口
public interface ICar {

    String getName();
}

 

//业务类实现
public class CarImpl implements ICar {

    @Override
    public String getName() {
        System.out.println("-------------执行方法-------------");
        return "abc";
    }
}

下面是代理处理器,和生成代理对象写一起,方便使用。

public class MyHandler implements InvocationHandler {

    private Object factory;

    public MyHandler(Object factory){
        this.factory = factory;
    }

    public Object getProxyInstance(){
        /*这里的 this 就是 invocationHandler*/
        return Proxy.newProxyInstance(factory.getClass().getClassLoader(),factory.getClass().getInterfaces(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        beforeHandle();
        Object result = method.invoke(factory,args);
        afterHandle();
        return result;
    }

    private void beforeHandle(){
        System.out.println("----------before----------");
    }

    private void afterHandle(){
        System.out.println("------------after-------------");
    }

最后是main测试方法

public class MyProxyMain {
    public static void main(String[] args) {
        ICar car = new CarImpl();
        MyHandler handler = new MyHandler(car);
        ICar carProxy = (ICar) handler.getProxyInstance();
        System.out.println("得到结果:"+carProxy.getName());
    }
}

运行结果

ccebf45cfe42cba265e8b18e8bb360fda3b.jpg

 

源码分析

Proxy.newProxyInstance  这个返回的代理对象为  $Proxy0,这是动态生成的类。

b2dc72811ee102c17c5b68f514f0d57fdce.jpg

 

这里主要看 getProxyClass0(loader, intfs) 怎么生成class

b3bc11c58fc825fe399219a26567371742f.jpg

 

再跟进去看

ed0ab14ca70288d87e1055a3d1d8a94e14f.jpg

那这里就把这个生成的class拿出来,写一段代码实现

/*生成代理类,并保存文件到本地*/
    public static void gengerateCalss(Class<?>[] interfaces){
        /*直接源码里拉出来*/
        byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                "com.sun.proxy.$Proxy0", interfaces, 17);
        File file=new File("C:/myTest/$Proxy0.class");
        FileOutputStream out = null;
        try {
            if(!file.exists()) {
                file.createNewFile();
            }
            out = new FileOutputStream(file);
            out.write(proxyClassFile);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out = null;
        }
    }

反编译这个类

public final class $Proxy0 extends Proxy
	implements ICar
{

	private static Method m1;
	private static Method m3;
	private static Method m2;
	private static Method m0;

	public $Proxy0(InvocationHandler invocationhandler)
	{
		super(invocationhandler);
	}

	public final boolean equals(Object obj)
	{
		try
		{
			return ((Boolean)super.h.invoke(this, m1, new Object[] {
				obj
			})).booleanValue();
		}
		catch (Error ) { }
		catch (Throwable throwable)
		{
			throw new UndeclaredThrowableException(throwable);
		}
	}

    /**这里有我业务里的接口方法 */
	public final String getName()
	{
		try
		{
            /**h 是代理处理器 invocationHandler,这里直接调用的处理的 invoke方法,这样就走通了 */
			return (String)super.h.invoke(this, m3, null);
		}
		catch (Error ) { }
		catch (Throwable throwable)
		{
			throw new UndeclaredThrowableException(throwable);
		}
	}

	public final String toString()
	{
		try
		{
			return (String)super.h.invoke(this, m2, null);
		}
		catch (Error ) { }
		catch (Throwable throwable)
		{
			throw new UndeclaredThrowableException(throwable);
		}
	}

	public final int hashCode()
	{
		try
		{
			return ((Integer)super.h.invoke(this, m0, null)).intValue();
		}
		catch (Error ) { }
		catch (Throwable throwable)
		{
			throw new UndeclaredThrowableException(throwable);
		}
	}

	static 
	{
		try
		{
			m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] {
				Class.forName("java.lang.Object")
			});
			m3 = Class.forName("com.useeinfo.oa.modules.base.myTest.myProxy.ICar").getMethod("getName", new Class[0]);
			m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
			m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
		}
		catch (NoSuchMethodException nosuchmethodexception)
		{
			throw new NoSuchMethodError(nosuchmethodexception.getMessage());
		}
		catch (ClassNotFoundException classnotfoundexception)
		{
			throw new NoClassDefFoundError(classnotfoundexception.getMessage());
		}
	}
}

 

转载于:https://my.oschina.net/u/1411360/blog/2987297

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值