Reputation: 2463
Question:
Is it possible to target multiple element types? (More than one, less than all)
Details:
I'm trying create an annotation that is only acceptable on Methods and Fields.
I know if I don't specify the @Target
annotation I can use my custom annotation on all elements. However, I want compile time safety on element types that conflict with my logic.
In C#/.NET
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method)]
public class MyAttribute : Attribute
{
...
Java Attempts
Multiple Target Annotations:
@Target(ElementType.METHOD)
@Target(ElementType.FIELD)
public @interface MyAnnotation
{
Compiler Error:
MyAnnotation.java:8: error: duplicate annotation
OR'd Values:
@Target(ElementType.METHOD | ElementType.FIELD)
public @interface MyAnnotation
{
Compiler Error:
MyAnnotation.java:7: error: bad operand types for binary operator '|'
Annotation Array
@Targets({@Target(ElementType.METHOD),@Target(ElementType.FIELD)})
public @interface MyAnnotation
{
Compiler Error:
MyAnnotation.java:7: error: cannot find symbol @Targets({@Target(ElementType.METHOD),@Target(ElementType.FIELD)})
^symbol: class Targets
Upvotes: 1
Views: 1762
Reputation: 1445
Java - The input is an array of ElementTypes. To define array values within an annotation, we comma separate the values within curly braces:
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface MyAnnotation {
}
Upvotes: 3