2020-10-12

2020-10-12  本文已影响0人  LoWang
package com.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyTest {
    public static void main(String[] args) {

        ProxyService service = (ProxyService)Proxy.newProxyInstance(ProxyTest.class.getClassLoader(),
            new Class[] {ProxyService.class}, new InvocationHandler() {
                String name;

                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().equals("name")) {
                        name = (String)args[0];
                    } else if (method.getName().equals("say")) {
                        System.out.println("my name is " + name);
                    }
                    return null;
                }
            });

        service.name("john");
        service.say();

        ProxyService service2 = (ProxyService)Proxy.newProxyInstance(ProxyTest.class.getClassLoader(),
            new Class[] {ProxyService.class}, new InvocationHandler() {
                String name;

                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().equals("name")) {
                        name = (String)args[0];
                    } else if (method.getName().equals("say")) {
                        System.out.println("my name is " + name);
                    }
                    return null;
                }
            });

        service2.name("xxx");
        service2.say();
        
        service.say();

    }

    public interface ProxyService {

        String name(String name);

        void say();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读