zoukankan      html  css  js  c++  java
  • JDK动态代理

    Jdk 动态代理通过反射包提供的方式,必须要借助一个借口才能产生反射对象

    1.定义接口:

    public interface HelloWorld 
    {
        public void sayHelloWorld();
        public void sayBye();
    }

    2.实现接口。

    public class HelloWorldImpl implements HelloWorld
    {
    
        @Override
        public void sayHelloWorld() 
        {
            System.out.println("hello world.....");
        }
    
        @Override
        public void sayBye() 
        {
            System.out.println("good bye.....");
        }
    
    }

    3. JDK 动态代理要实现逻辑类,必须去实现java.lang.reflect.InvocationHandler接口, 里面定义了invoke方法。

    public class JdkProxy implements InvocationHandler
    {    
            //真实对象
        private Object target;
        
            //返回代理对象
        public Object bind(Object target)
        {
            this.target=target;
            return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
        }
            //代理方法逻辑
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("entrance proxy method....");
            System.out.println("before call real obj method.....");
            Object obj = method.invoke(target, args);//相当调用sayHello/bye
            System.out.println("after real obj.....");
            return obj;
        }
    }

    4.测试类:

    public class JdkProxyTest {
    
        public static void main(String[] args) 
        {
            JdkProxy jdk = new JdkProxy();
            HelloWorld hellow = (HelloWorld) jdk.bind(new HelloWorldImpl());
            hellow.sayHelloWorld();
            hellow.sayBye();
        }
    
    }
    输出:
    entrance proxy method....
    before call real obj method.....
    hello world.....
    after real obj.....
    entrance proxy method....
    before call real obj method.....
    good bye.....
    after real obj.....
  • 相关阅读:
    支持向量机通俗导论(理解SVM的三层境地)
    ComponentName的意思
    图像切割之(五)活动轮廓模型之Snake模型简单介绍
    TraceView总结
    Redis:百科
    Redis:目录
    Redis: temple
    软件-操作系统-服务器:Nginx(engine X)
    软件-数学软件:Maple
    软件-数学软件:Mathematica
  • 原文地址:https://www.cnblogs.com/daxiong225/p/9900393.html
Copyright © 2011-2022 走看看