Quick revision
The short answer
We declare @interface Retry { int times() default 3; } with @Retention(RUNTIME) so reflection can see it and @Target(METHOD) so it can only go on methods. The helper reads it with method.getAnnotation(Retry.class), treats a missing annotation as one attempt, and calls method.invoke in a loop, unwrapping InvocationTargetException to get the method's real exception. After the last attempt it rethrows that last failure. Annotation members can only be primitives, String, Class, enums, other annotations, or arrays of those, which is why the configuration is an int.
What to remember
In this answer, we declared @Retry with RUNTIME retention and a METHOD target, and wrote a helper that reads it with getAnnotation, treats a missing annotation as one attempt, and calls method.invoke in a loop. We unwrapped InvocationTargetException to retry on, and rethrow, the method's real exception, and rethrew the last failure after the final attempt. We also saw that annotation members are limited to primitives, String, Class, enums, annotations and arrays of those, so a Duration becomes a number or a parsable string, and that a Spring aspect binds the annotation and calls proceed() instead.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We declare @interface Retry { int times() default 3; } with @Retention(RUNTIME) so reflection can see it and @Target(METHOD) so it can only go on methods. The helper reads it with method.getAnnotation(Retry.class), treats a missing annotation as one attempt, and calls method.invoke in a loop, unwrapping InvocationTargetException to get the method's real exception. After the last attempt it rethrows that last failure. Annotation members can only be primitives, String, Class, enums, other annotations, or arrays of those, which is why the configuration is an int.
Why this question is asked
Writing a small annotation and the code that honours it is the best way to understand how frameworks like Spring Retry or Resilience4j work underneath. Interviewers ask for it because it touches several things at once: meta-annotations, reflection, the way invoke wraps exceptions, and the restrictions on annotation members. In this answer, we will declare the annotation, write the reflective helper step by step, see why InvocationTargetException must be unwrapped, look at what types annotation members may have, and then see how the same thing looks as a Spring aspect.
1Declaring the Annotation
Two meta-annotations are essential. @Retention(RetentionPolicy.RUNTIME) keeps the annotation visible to reflection; without it the default is CLASS, and getAnnotation would always return null. @Target(ElementType.METHOD) makes the compiler reject the annotation anywhere else, so nobody puts it on a class expecting it to work.
The on() member is optional for the question, but it shows a useful idea: retrying every exception is rarely right. An IllegalArgumentException will fail the same way every time, while a timeout might succeed on the next attempt. The default keeps the example simple by retrying any Exception, and a real method would narrow it, for example @Retry(times = 3, on = IOException.class).
2Writing the Reflective Helper
The helper takes the target object, the Method and its arguments. It reads the annotation once, decides how many attempts to make, and loops.
Notice three decisions. A missing annotation means one attempt, so the helper is safe to call on any method. times() is clamped to at least 1, so @Retry(times = 0) cannot skip the call entirely. And reflection problems, such as calling a private method without access, are not retried, because they would fail identically every time.
3Trying It Out
Here is a client that fails twice and then succeeds, and what the helper does with it.
- Read @Retry from the Methodnull means one attempt
- method.invoke(target, args)
- Threw InvocationTargetException?YesUnwrap getCause()NoReturn the result
- Retryable and attempts left?YesTry againNoRethrow the real exception
4 steps in order. Play them, or step through them one at a time.
In real code we would also wait between attempts, usually with an increasing delay such as 100, 200 and 400 milliseconds, so a struggling service gets time to recover. That would be another int member, for example backoffMillis.
4Why We Unwrap InvocationTargetException
Method.invoke does not let the called method's exception escape as it is. It wraps whatever the method threw in an InvocationTargetException and throws that instead. That way, callers can tell the method failed apart from reflection itself failing, which shows up as IllegalAccessException or IllegalArgumentException.
If we forgot to unwrap, the caller of our helper would see InvocationTargetException with the real IOException hidden inside, and our retry rule on() would compare the wrong type. So we always take getCause(), decide on that, and rethrow that. The helper declares throws Throwable because the target method could throw anything, including checked exceptions.
5What Types Annotation Members May Have
Annotation members are restricted to primitives, String, Class (optionally with a bound like Class<? extends Throwable>), enums, other annotation types, and one-dimensional arrays of those. Their values must be compile-time constants, because the compiler writes them directly into the class file, and the JVM rebuilds them when reflection asks.
So there is no Duration member. The usual workarounds are a number with a TimeUnit, or an ISO-8601 string such as PT0.1S parsed at run time; Spring Retry's annotations, for example, offer both numeric delays and string expressions.
6Follow-up questions
Why can an annotation attribute not be of type Duration?
Because annotation values must be compile-time constants that the compiler can store in the class file's constant pool, and the language only allows primitives, String, Class, enums, annotations and arrays of those. A Duration is an ordinary object created at run time, so there is no way to write a Duration constant into a class file. We use a long with a TimeUnit, or a String that we parse with Duration.parse.
How would this be done with a Spring aspect instead?
We would write an @Aspect with @Around("@annotation(retry)") and a parameter Retry retry, so Spring binds the annotation for us. Inside, we loop calling pjp.proceed(), which throws the real exception directly, so there is no InvocationTargetException to unwrap. The aspect then applies to every Spring bean method annotated @Retry, with the usual proxy limits: no self-calls and no private or final methods. In practice we would use Spring Retry's @Retryable, or the @Retryable in Spring Framework 7's core resilience support, rather than our own (check your version).
Is retrying safe for every method?
No. Retrying is only safe for idempotent operations, those that give the same outcome when repeated, such as a read or a payment call with an idempotency key. Retrying a non-idempotent call, like charging a card without a key, can charge twice when the first attempt actually succeeded but its response timed out.
7Conclusion
In this answer, we declared @Retry with RUNTIME retention and a METHOD target, and wrote a helper that reads it with getAnnotation, treats a missing annotation as one attempt, and calls method.invoke in a loop. We unwrapped InvocationTargetException to retry on, and rethrow, the method's real exception, and rethrew the last failure after the final attempt. We also saw that annotation members are limited to primitives, String, Class, enums, annotations and arrays of those, so a Duration becomes a number or a parsable string, and that a Spring aspect binds the annotation and calls proceed() instead.
Open with
First the annotation: @Retention(RetentionPolicy.RUNTIME) so reflection can see it, because the default CLASS retention would make getAnnotation return null, and @Target(ElementType.METHOD) so it can only go on methods.
Then, if they want more
Then @interface Retry with int times() default 3. I might also add an array of exception classes to retry on, because retrying something like an IllegalArgumentException makes no sense. The helper takes the target, the Method and the arguments. It calls method.getAnnotation(Retry.class), and if that is null it just calls the method once.
Otherwise it loops up to times, calling method.invoke. The important detail is that invoke wraps whatever the method threw in an InvocationTargetException, so I catch that and take getCause to get the real exception. I decide whether to retry based on that cause, and after the last attempt I rethrow that last failure, not the wrapper.
Reflection errors like IllegalAccessException I would not retry, since they are bugs. In real code I would add a backoff between attempts. And on member types: annotation members can only be primitives, String, Class, enums, other annotations or arrays of those, because the values are compile-time constants stored in the class file.
That is why you cannot have a Duration member; I would use a long with a TimeUnit or an ISO string. As a Spring aspect, it would be @Around with @annotation(retry), looping on proceed.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 7
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a custom annotation @Retry(times = 3) usable only on methods and readable at run...": https://scrivio-interview-library.netlify.app/java/annotations/9cefa6ecd9/