简体   繁体   English

Java批注:将批注属性的值传递给另一个批注

[英]Java annotations: pass value of annotation attribute to another annotation

I have interface Resource and several classes implementing it, for example Audio , Video ... Further, I have created custom annotation MyAnnotation with Class type param: 我有接口Resource和几个实现它的类,例如AudioVideo 。此外,我还创建了带有Class类型param的自定义注释MyAnnotation

 @MyAnnotation(type = Audio.class)
 class Audio {
 ...
 }

 @MyAnnotation(type = Video.class)
 class Video{
 ...
 }

In some other place in code I have to use Interface Resource as a returned type: 在代码的其他地方,我必须使用接口资源作为返回类型:

public class Operations<T extends Resource> {
    ....
    @OtherAnnotation(type = Audio.class (if audio), type = Video.class (if video) )
    T getResource();
    ....
}

The question is how to appropriatelly annotate annotation @OtherAnnotation depending of what kind of Resource type will be returned ? 问题是如何根据返回的资源类型适当地注释@OtherAnnotation

What you are asking is for dynamic values for annotation attributes. 您要提供的是注释属性的动态值。

However annotations can only be set at compile time which is the reason why their values can only be compile time constants. 但是,注释只能在编译时设置,这就是为什么它们的值只能是编译时常数的原因。 You may only read them at runtime. 您只能在运行时阅读它们。


There was a similar question in which someone tried to generate the annotation value , it's answer explains why there is no way to dynamically generate a value used in annotation in a bit more detail. 还有一个类似的问题,有人试图生成注释值, 它的答案解释了为什么没有办法更动态地生成注释中使用的值。 In that question there was an attempt to use a final class variable generated with a static method. 在该问题中,尝试使用由静态方法生成的最终类变量。


There are annotation processors which offer a bit more flexibility by handling placeholders. 有注释处理器通过处理占位符提供了更多的灵活性。 However i don't think this fits your case, as you want the dynamic values at runtime. 但是我认为这不适合您的情况,因为您希望在运行时提供动态值。

This answer refers to spring's use of the expression language for the Value annotation in which the placeholder ( @Value("#{systemProperties.dbName})" ) gets overrided with the data from one of the property sources defined ( example in spring boot ) 这个答案是指Spring对Value注释使用表达式语言 ,其中占位符( @Value("#{systemProperties.dbName})" )被定义的属性源之一中的数据覆盖( 例如spring boot )。

In any case, you will have to rethink your architecture a bit. 无论如何,您将不得不重新考虑一下您的体系结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM