terface POST {
String value() default "";
}
public interface Service {
//用POST注解声明请求的方式和相对路径
@POST("/login")
//@Query注解声明请求的参数名
void login(@Query("username")String username,
@Query("password")String password);
}
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动态代理
代理模式
|