Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is to possible to call annotation interfaces' default methods?

Tags:

java

Given an annotation interface such as

@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidFileType {

    String[] value() default {
        MediaType.TEXT_PLAIN_VALUE,
        MediaType.APPLICATION_PDF_VALUE,
        MediaType.IMAGE_GIF_VALUE
    };

    String message() default "{com.example.invalidFileType}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Is it possible to get the default list of file types from outside the interface, i.e. the string array returned by value()?

like image 624
Dónal Avatar asked Oct 28 '25 10:10

Dónal


1 Answers

Yeap, you need to use reflection to do so, here is a simple example (note that I removed the MediaType as I don't know from which library you are importing it)

@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidFileType {
    String[] value() default {
        "value 1",
        "value 2",
        "value 3"
    };
}

Here is a test class to read it (I added the imports)

import java.lang.reflect.Method;
import java.util.Arrays;
public class Test {
    public static void main(String[] args) throws NoSuchMethodException, SecurityException {
        Class<?> annotationClass = ValidFileType.class;
        Method valueMethod = annotationClass.getMethod("value");
        //You might need to change this line 
        //a bit to convert the MediaType to string (just toString might work)        
        String[] defaultValues = (String[]) valueMethod.getDefaultValue();
        System.out.println("Valid file types: " + Arrays.toString(defaultValues));
    }
}

It then prints:

Valid file types: [value 1, value 2, value 3]
like image 76
Jorge Campos Avatar answered Oct 31 '25 00:10

Jorge Campos