1

I know that there is no java annotation inheritance. But is it possible to do something like that in java?

@TopAnnot({
    @SubAnnot("value1"),
    @SubAnnot("value2"),
    @AnotherSubAnnot("value3"),
    @SubAnnot("value4")
})
public void aMethod(String param) { ... }

The order of the @SubAnnot and @AnotherSubAnnot is important.

So, the following solution, won't have the same meaning, as I can't maintain the order of the annotations:

@TopAnnot(
    subAnnot = {
        @SubAnnot("value1"),
        @SubAnnot("value2"),
        @SubAnnot("value4")
    },
    annotherAnnot = {
        @AnotherSubAnnot("value3")
    }
)
public void aMethod(String param) { ... }

Another solution should have been the following, but it is far more complex to write and not really easy to understand:

@TopAnnot({
    @MyAnnot(type=AnnotType.SubAnnot, value = "value1"),
    @MyAnnot(type=AnnotType.SubAnnot, value = "value2"),
    @MyAnnot(type=AnnotType.AnnotherSubAnnot, value = "value3"),
    @MyAnnot(type=AnnotType.SubAnnot, value = "value3")
})
public void aMethod(String param) { ... }

Is there any easier solution?

Community
  • 1
  • 1
fluminis
  • 3,575
  • 4
  • 34
  • 47

1 Answers1

0

You can add some readability by using Java 8 repeating annotations, but that won't solve the actual issue. It still uses container annotations that only retain the order of declaration per type. So you can make it look like it the first example, but you still don't know the actual order at runtime.

@SubAnnot("value1"),
@SubAnnot("value2"),
@AnotherSubAnnot("value3"),
@SubAnnot("value4")
public void aMethod(String param) { ... }

I think there is no nice solution for this at runtime. It should be possible to get the order of declaration at compile time though, if you have access to the source code.

If you need a solution at runtime, you probably either have to use a type field like in your example or add a another field that declares the order explicitly, e.g.:

@SubAnnot(id=1, value="value1")
@AnotherSubAnnot(id=2, value="value2"))
@SubAnnot(id=3, value="value3")
kapex
  • 28,903
  • 6
  • 107
  • 121