JDK动态代理 思路整理

2022-10-28 08:48:46 浏览数 (1)

JDK动态代理 思路整理

1.提供一个接口和实现类

代码语言:javascript复制
public interface Skill {
    void run();
    void swim();
}

public class Althletes implements Skill{

    @Override
    public void run() {
        System.out.println("Run fast");
    }

    @Override
    public void swim() {
        System.out.println("Swim fast");
    }
}

2.创建代理类 传入目标对象

代码语言:javascript复制
public class AlthleteProxy {
    public Skill AlthleteProxy(Althletes obj) {
        return (Skill) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces()
            , ((proxy, method, args) ->  {
            System.out.println("Start");
            Object result = method.invoke(proxy, args);
            System.out.println("Finish");
            return result;
            };));
    }
}

3.调用代理对象

代码语言:javascript复制
public class Main { 
    public static void main(String[] args) {
        Skill s = new AlthleteProxy(new Althletes);
        s.run();
        s.swim();
    }
}

0 人点赞