Java 创建一个包含注释值的最终字段,以便在许多方法上重用它

use*_*526 5 java annotations

在Java中是否可以将注释值存储在常量字段(或类似字段)中,以便在需要的每个方法上重用它?例如,如果我有这个带注释的方法:

@CustomAnnotations({
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    ...
    @CustomAnnotation(..)
})
private static MyReturnValue doSomething(){
    ..
}
Run Code Online (Sandbox Code Playgroud)

我想向同一个类中的许多方法添加相同的注释,而不需要为每个方法剪切和粘贴它,是否可以定义一个字段,例如:

private static final Something annotationsConstant = {
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    @CustomAnnotation(..),
    ...
    @CustomAnnotation(..)
}

@CustomAnnotatins(annotationsConstant)    
private static MyReturnValue doSomething(){
    ..
}

@CustomAnnotatins(annotationsConstant)    
private static MyReturnValue anotherMethod(){
    ..
}
Run Code Online (Sandbox Code Playgroud)

如果是,包含注释的字段的数据类型是什么?如果没有,是否有另一种方法无需为每个方法重写相同的注释?

whi*_*mot 6

听起来您想要一个注释来扩展其他注释。遗憾的是,这在 Java 中是不可能的。例如看到这个问题

然而,有一些方法可以实现类似的目标。尝试研究Spring 如何编写注释