- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Type dependent annotations?
Sat, 2008-12-20, 04:29
Hello,
Today you have the following possibilities to specify the element to which an annotation is applicable:
I sketched how it could look like in the example below:
Today you have the following possibilities to specify the element to which an annotation is applicable:
- @Target(ElementType.TYPE)—can be applied to any element of a class
- @Target(ElementType.FIELD)—can be applied to a field or property
- @Target(ElementType.METHOD)—can be applied to a method level annotation
- @Target(ElementType.PARAMETER)—can be applied to the parameters of a method
- @Target(ElementType.CONSTRUCTOR)—can be applied to constructors
- @Target(ElementType.LOCAL_VARIABLE)—can be applied to local variables
- @Target(ElementType.ANNOTATION_TYPE)—indicates that the declared type itself is an annotation type
- @Target(T.Field)—can be applied to a field of type T
I sketched how it could look like in the example below:
@Retention(RetentionPolicy.RUNTIME)
@Target(T.FIELD, required = true)
public @interface TAnnotation {
public String a();
public String b();
}
class X {
@TAnnotation(a="Hello", b="World") // ok
val f = new T
@TAnnotation(a="Hello", b="World") // error: annotation only valid for fileds of type T, found U
val g = new U
// error: TAnnotation annotation missing
val h = new T
}
Is there a way to support this without breaking everything?
Thanks,
Sebastien