Java动态代理--JDK动态代理

package com.mzsx.proxy;
public interface FunctionServer {
    void creatdDoc(int count);
                                                          
    void removeDoc(int count);
}


package com.mzsx.proxy;
public class FunctionServerImp implements FunctionServer {
    @Override
    public void creatdDoc(int count) {
        System.out.println("创建了"+count+"对象。。。。。。。");
    }
    @Override
    public void removeDoc(int count) {
        System.out.println("删除了"+count+"对象。。。。。。。");
    }
}


package com.mzsx.proxy;
public class Porformant {
    private long start;
    private long end;
    public  void start(){
        System.out.println("执行start。。。。。");
        start =System.currentTimeMillis();
    }
                                            
    public void end(){
        end=System.currentTimeMillis();
        System.out.println("耗时"+(end-start)+"ms........");
    }
}



package com.mzsx.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class FunctionHandler implements InvocationHandler {
    private Object target;
    public FunctionHandler(Object target){
        this.target=target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("==============:"+proxy.getClass().getName());
        Porformant porformant=new Porformant();
        porformant.start();
                                              
        Object object=method.invoke(target, args);
        porformant.end();
                                              
        return object;
    }
                                          
}
package com.mzsx.proxy;
import java.lang.reflect.Proxy;
public class Functiontest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FunctionServer functionServer=new FunctionServerImp();
        FunctionHandler functionHandler=new FunctionHandler(functionServer);
        FunctionServer proxy=(FunctionServer)Proxy.newProxyInstance(functionServer.getClass().getClassLoader(), functionServer.getClass().getInterfaces(), functionHandler);
        proxy.creatdDoc(10);
        System.out.println("-------------------------------------------");
        proxy.removeDoc(20);
                                            
                                            
    }
}


结果:

==============:$Proxy0
执行start。。。。。
创建了10对象。。。。。。。
耗时0ms........
-------------------------------------------
==============:$Proxy0
执行start。。。。。
删除了20对象。。。。。。。
耗时1ms........


你可能感兴趣的:(java,动态代理,JDK动态代理)