美文网首页
2020-10-12

2020-10-12

作者: LoWang | 来源:发表于2020-10-12 14:50 被阅读0次
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();
    }
}

相关文章

网友评论

      本文标题:2020-10-12

      本文链接:https://www.haomeiwen.com/subject/sboupktx.html