動態代理 Proxy.newProxyInstance

動態代理使用

interface UserService{
    void login(User user);
    void register(User user);
}

class UserServiceImpl implements UserService {
    @Override
    void register(User user) {
        // 這裏是原本的基礎業務實現
    }

    @Override
    void login(User user) {
        // 這裏是原本的基礎業務實現
    }
}

class UserServiceInterceptor implements InvocationHandler {
    private Object realObj;
    
    public UserServiceInterceptor(Object realObj) {
        super();
        this.realObj = realObj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(args != null && args.length > 0 && args[0] instanceof User) {
            // 無侵入式增加代碼
            if(user.getName().getPassword().length() <= 6 && method.getName().equals("login")) {
                throw new RuntimeException("密碼長度必須大於6");
            }
            
            Object result = method.invoke(realObj, args);
            return result;
        }
    }
}


// 如何使用
public static void main(String[] args) {
    UserService userService = new UserServiceImpl();
    InvocationHandler userServiceInterceptor = new UserServiceInterceptor(userService);

    UserService userServiceProxy = Proxy.newProxyInstance(userService.getClass().getClassLoader, userService.getClass().getInterfaces(), userServiceInterceptor);
    // 使用時直接通過userServiceProxy進行調用
    userServiceProxy.login(new User());
}

使用很簡單,就是熟悉下InvocationHandler Proxy.newProxyInstance。

InvocationHandler實現了無侵入式的增加被代理類的功能,Proxy.newProxyInstance利用傳入參數,運行時動態生成被代理類的實際對象(如何利用傳入參數生成對象,涉及的知識點是類加載過程)。

在本人看來,動態代理最大的用處就是上面的加黑斜體:無侵入式的增加被代理類的功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章