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

    1.HelloWorld

    package reflect.proxy;
    
    public interface HelloWorld {
        void print();
    }

    2.HelloWorldImpl

    package reflect.proxy;
    
    public class HelloWorldImpl implements HelloWorld{
    
        @Override
        public void print() {
            // TODO Auto-generated method stub
            System.out.println("hello world!");
        }
        
    }

    3.HelloWorldInvocationHandle

    package reflect.proxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    public class HelloWorldInvocationHandle implements InvocationHandler{
        private HelloWorld helloWorld;
        public HelloWorldInvocationHandle(HelloWorld helloWorld) {
            this.helloWorld = helloWorld;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            // TODO Auto-generated method stub
            System.out.println("动态代理-begin");
            Object result = method.invoke(helloWorld, args);
            System.out.println("动态代理-end");
            return result;
        }
    
    }

    4.HelloWorldProxyFactory

    package reflect.proxy;
    
    import java.lang.reflect.Proxy;
    
    public class HelloWorldProxyFactory {
        public static HelloWorld getProxy(HelloWorld helloWorld) {
            HelloWorldInvocationHandle handle = new HelloWorldInvocationHandle(helloWorld);
            Object obj = Proxy.newProxyInstance(helloWorld.getClass().getClassLoader(), new Class[]{HelloWorld.class}, handle);
            return (HelloWorld)obj;
        }
        
        public static void main(String[] args) {
            HelloWorld helloWorld = new HelloWorldImpl();
            HelloWorld proxy = HelloWorldProxyFactory.getProxy(helloWorld);
            System.out.println(proxy.getClass().getName());
            proxy.print();
        }
    }
  • 相关阅读:
    进程上下文VS中断上下文
    字符串分割处理
    C++接收含有空格的字符串
    TLS分析
    位运算之bit_xor、bit_not、bit_and、bit_or
    GET和POST区别
    我的 HTTP/1.1 好慢啊!
    HTTP/2与HTTP/1的比较
    C++11新特性之一— auto 和 decltype 区别和联系
    C++ tuple元组的基本用法(总结)
  • 原文地址:https://www.cnblogs.com/jerry19890622/p/3287326.html
Copyright © 2011-2022 走看看