给定一个注释接口,例如
@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 {};
}
是否可以从接口外部获取默认的文件类型列表,即
value()
返回的字符串数组?
是的,您需要使用反射来执行此操作,这是一个简单的示例(请注意,我删除了
MediaType
,因为我不知道您从哪个库导入它)
@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidFileType {
String[] value() default {
"value 1",
"value 2",
"value 3"
};
}
这是一个测试类来读取它(我添加了导入)
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));
}
}
然后打印:
Valid file types: [value 1, value 2, value 3]