Java中的Proxy对象(代理)

Star

public class Star implements Skill {
    String name;

    public Star(String name) {
        this.name = name;
    }

    @Override
    public void sing() {
        System.out.println("唱歌");
    }

    @Override
    public void jump() {
        System.out.println("跳舞");
    }
}

StarAgent

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

public class StarAgentProxy {
    public static Skill getProxy(Star s) {
        return (Skill)Proxy.newProxyInstance(s.getClass().getClassLoader(), s.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("表演开始");
                Object rs = method.invoke(s,args);
                System.out.println("表演结束.");
                return rs;
            }
        });
    }
}

posted @ 2022-09-02 22:06  ajajaz  阅读(36)  评论(0编辑  收藏  举报