gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:06:46 25 4
gpt4 key购买 nike

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

@CustomAnnotations({
@CustomAnnotation(..),
@CustomAnnotation(..),
@CustomAnnotation(..),
@CustomAnnotation(..),
...
@CustomAnnotation(..)
})
private static MyReturnValue doSomething(){
..
}

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

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

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

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

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

最佳答案

听起来您希望一个注解扩展其他注解。遗憾的是,这在 Java 中是不可能的。例如参见 this question .

但是,有一些方法可以实现类似的效果。尝试研究如何 Spring compose annotations .

关于Java 创建一个包含注释值的 final 字段以在许多方法上重用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34138176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com