设为首页 加入收藏

TOP

java中的代理模式(二)
2017-10-13 10:39:14 】 浏览:6958
Tags:java 代理 模式
terface
POST { String value() default ""; }
  • Service接口
public interface Service {
    //用POST注解声明请求的方式和相对路径
    @POST("/login")
    //@Query注解声明请求的参数名
    void login(@Query("username")String username, 
            @Query("password")String password);
}
  • Main
public class Main {

    public static void main(String[] args) {
        // 动态获取Service接口的代理
        Service service = (Service) Proxy.newProxyInstance(Service.class.getClassLoader(),
                new Class[] { Service.class }, new InvocationHandler() {

                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // 通过注解获取请求的相对路径
                        String retativePath = ((POST) method.getAnnotations()[0]).value();
                        System.out.println("relative path: " + retativePath);
                        // 获取参数的注解
                        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
                        // 通过参数的注解获取请求参数
                        for (int i = 0; i < parameterAnnotations.length; i++) {
                            if (parameterAnnotations[i].length != 0) {
                                for (int j = 0; j < parameterAnnotations[i].length; j++) {
                                    Query query = (Query) parameterAnnotations[i][j];
                                    System.out.println(query.value() + ": " + args[i].toString());
                                }
                            }
                        }
                        return null;
                    }
                });
        // 调用代理对象的方法
        service.login("hello", "world");
    }

}

参考

JAVA动态代理

代理模式

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇男人历史外,一缕女性芬芳 下一篇数据可视化工具

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目