public class DynamicProxy implements InvocationHandler {
private final Object subject;
private static final int RETRY_MAX_COUNT = 3;
public DynamicProxy(Object subject) {
this.subject = subject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
int times = 0;
while (times < RETRY_MAX_COUNT) {
try {
// 当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用
return method.invoke(subject, args);
} catch (Exception e) {
if (e.getCause() instanceof MyRetryException) {
MyRetryException myRetryException = (MyRetryException) e.getCause();
if (myRetryException.getCode() == -1) {
// 触发重试机制
times++;
System.out.println("第" + times + "次重试异常:" + e.getCause());
} else {
// 终止重试
System.out.println("返回code不匹配,终止重试,e:" + e.getMessage());
return null;
}
} else {
// 终止重试
System.out.println("执行失败,终止重试,e:" + e.getMessage());
return null;