Java静态代理与动态代理
Posted xiaoxuelilei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java静态代理与动态代理相关的知识,希望对你有一定的参考价值。
package com.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface ProductFactory
public void productCloth();
class NikeProductFactory implements ProductFactory
@Override
public void productCloth()
// TODO Auto-generated method stub
System.out.println("this is nike productor");
/**
* 静态代理
* @author lilei7
*
*/
class StaticProxy implements ProductFactory
private ProductFactory o ;
public StaticProxy(ProductFactory o)
this.o=o;
@Override
public void productCloth()
// TODO Auto-generated method stub
System.out.println("this is proxy");
o.productCloth();
/**
* 动态代理
* @author lilei7
*
*/
class DynamicProxy implements InvocationHandler
Object obj ;
public Object bindObject(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
// TODO Auto-generated method stub
System.out.println(obj);
return method.invoke(obj, args);
public class TestProxy
public static void main(String[] args)
//静态代理测试方法
NikeProductFactory nike = new NikeProductFactory();
StaticProxy staticProxy = new StaticProxy(nike);
staticProxy.productCloth();
//动态代理测试方法
DynamicProxy dynamicProxy = new DynamicProxy();
Object o = dynamicProxy.bindObject(nike);
ProductFactory factory = (ProductFactory)o;
factory.productCloth();
以上是关于Java静态代理与动态代理的主要内容,如果未能解决你的问题,请参考以下文章