java注解使用问题? 400 报错
先描述下问题吧:有些时候有些事情在可能会失败,这个时候就得去重试。写个简单的例子:
1. 注解类
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Retry { int times() default 1; }
2. 任务类
public class Test { @Retry(times = 5) public void doJob(String job) { System.out.println(job); } }
public class RetryManager { public void doRetry(Class<?> objectClazz, String methodName, Object... args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { Object instance = objectClazz.getConstructor().newInstance(); Class<?>[] fileTypeArray = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { fileTypeArray[i] = args[i].getClass(); } Method method = objectClazz.getMethod(methodName, fileTypeArray); int times = method.getAnnotation(Retry.class).times(); while (times-- > 0) { try { method.invoke(instance, args); break; } catch (Exception e) { System.out.println("error happend, retry"); } } } public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { RetryManager manager = new RetryManager(); manager.doRetry(Test.class, "doJob", "=== just eating ==="); } }
我想要的是直接调用任务类的背注解了的方法,然后就会执行上面处理类的方法,可以有办法实现么。
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Retry { int times() default 1; }
public interface ToDo { @Retry(times = 5) void doSomething(String thing); }
public class Test implements ToDo { @Override public void doSomething(String thing) { System.out.println(thing); throw new RuntimeException(); } }
public class RetryProxy implements InvocationHandler { private Object object; @SuppressWarnings("unchecked") public <T> T getInstance(T t) { object = t; return (T) Proxy.newProxyInstance(t.getClass().getClassLoader(), t.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Class<?>[] fileTypeArray = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { fileTypeArray[i] = args[i].getClass(); } int times = method.getAnnotation(Retry.class).times(); Object result = null; while (times-- > 0) { try { result = method.invoke(object, args); break; } catch (Exception e) { System.out.println("error happend, retry"); } } return result; } public static void main(String[] args) { ToDo toDo = new RetryProxy().getInstance(new Test()); toDo.doSomething("== eat anything =="); } }
没看懂2段代码在使用上有什么不同之处
###### @Maxwell1987 哦,是第一次弄错了,后来立马换了,估计服务器反应慢######回复 @IncRediblE : 是你换了图片还是昨天我看花眼了?昨天仔细看了几次两个main方法里面写的是一样的,才有此一问的。######功能当然一样,主要是看main方法里的调用,是用动态代理后有表面上的调用就很简洁了集结各类场景实战经验,助你开发运维畅行无忧