Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an object in a Java annotation?

I am making a Test annotation, and I want to be able for the user to specify an expected return value.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
    Object value() default null;
    Class<? extends Throwable> exception() default NoException.class;
    int timeout() default 0;
}

As I know, you cannot specify Object as the return type in annotation methods.

I am wondering if there is a return type which allows primitives AND strings to be returned.

If not, is it possible to create? Thank you.

like image 424
Thomas Nappo Avatar asked Sep 05 '25 03:09

Thomas Nappo


1 Answers

In short no. The oracle docs explain this

Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. Methods can have default values

See here for the Oracle documents on this.

If you could pass an object what would be the syntax? The items that are passed have to be constants which is why there is the restriction

like image 160
RNJ Avatar answered Sep 08 '25 00:09

RNJ