Why are java annotation attributes have limitations?

I noticed that if I create an annotation:

public @interface NullableTypeOverride { NullableType hibernateTypeOverride(); } 

I have limited annotation attribute capabilities. The above code will not work because annotations accept only primitive String or Class types for their attributes.

So, in this case, I cannot use this annotation as follows:

 @NullableTypeOverride(hibernateTypeOverride = Hibernate.INTEGER) private Long distance; 

I assume it has something to do with compile time and runtime, but I'm not quite sure. So what is the reason for this limitation and how can I get around it?

+6
source share
1 answer

JLS state

This is a compile-time error if the return type of the method declared in the annotation type is not one of the following: primitive type, String, Class, any parameterized class call, enumeration type (ยง8.9), annotation type or array type (ยง10), type The item is one of the previous types.

The reason for this is that annotations must have a constant meaning. If you provide a link to an object that is subject to change, you will have problems. This only applies to saving the RUNTIME annotation.

 public class Person { public String name; } @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { Person person(); } @MyAnnotation(person = ???) // how to guarantee it won't change at runtime? public void method1() {...} 

What should this value be? And how can lib libraries reflect?

 MyAnnotation annotation = method.getAnnotation(MyAnnotation.class); annotation.person(); // should be the same value every time 

Remember that annotations must be metadata.

+5
source

Source: https://habr.com/ru/post/953718/


All Articles