3

I have interface Resource and several classes implementing it, for example Audio, Video... Further, I have created custom annotation MyAnnotation with Class type param:

 @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 ?

user109447
  • 1,069
  • 1
  • 10
  • 20

1 Answers1

3

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 )

In any case, you will have to rethink your architecture a bit.

Community
  • 1
  • 1
Laurentiu L.
  • 6,566
  • 1
  • 34
  • 60