简体   繁体   中英

How can I define my Custom Annotation to use a subset of target elements?

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

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 {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM