【Java】【反射】动态代理

动态代理

public class Test {
    public static void main(String[] args) {
        StudentImp si = new StudentImp();
        si.login();
        si.submit();
    
        System.out.println("-------------------------------");
        MyInvocationHandler m = new MyInvocationHandler(si);
        Student s = (Student) Proxy.newProxyInstance(si.getClass().getClassLoader(), si.getClass().getInterfaces(), m);
    
        s.login();
        s.submit();
    }
}

class MyInvocationHandler implements InvocationHandler {
    private Object target;
    
    public MyInvocationHandler(Object target) {
        this.target = target;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("权限检查");
        method.invoke(target, args);
        System.out.println("写入日志");
        return null;
    }
}

class StudentImp implements Student {
    @Override
    public void login() {
        System.out.println("登陆");
    }
    
    @Override
    public void submit() {
        System.out.println("提交");
    }
}

interface Student {
    public void login();
    
    public void submit();
}

你可能感兴趣的:(【Java】【反射】动态代理)