#Annotations - interface as attribute type

1 messages · Page 1 of 1 (latest)

patent prawn
#

Hey, I haven't found any useful resources on this. Maybe I'm using the wrong keywords, so I figured I should ask here:

Why do annotations not allow interfaces as attribute types?

public interface MyInterface {
    String upper();
}

public @interface MyAnnotation {
    MyInterface value(); // Invalid type 'MyInterface' for annotation member
}

For some more context: I actually want to pass an enum, but use an interface to define a standard method (implementation can vary).

This is just an example:

public enum MyEnum implements MyInterface {
    1("One"),
    2("Two");

    private String string;

    public MyEnum(String string) {
        this.string = string;
    }

    @Override
    public String upper() {
        return string.toUpperCase();
    }
}

@MyAnnotation(MyEnum.1)
public class MyClass {
    // ... could then get the value and use `MyInterface#upper`
}
sinful flowerBOT
#

This post has been reserved for your question.

Hey @patent prawn! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

coral star
#

Annotations are fully defined at compile time. Like, what they are is exactly how they're written. Running the program can't change anything about them.

And while an enum is a compile-time constant, a general type like an interface or class, isn't.

#

Like if it was accepted, then I could do:

public class MyClass implements MyInterface {
  private final String salt;
  public MyClass(String salt) {
    this.salt = salt + LocalDateTime.now();
  }
  @Override
  public String upper() {
    return salt;
  }
}
#

and then

@MyAnnotation(new MyClass("kyo-chan"))
public class MyClass {
    // ... could then get the value and use `MyInterface#upper`
}
#

Which is completely contradictory with the concept of annotations

patent prawn
#

Right, I understand the value has to be a constant, but in my example the interface is implemented by an enum, and I know interfaces can also be implemented by normal classes, like in you example.

But since enums can implement interfaces, why disallow it completely?

coral star
#

Because other things can also implement interfaces

patent prawn
#

When the interface is applied to an enum it would be a constant too, no?
If I drop the interface and implement the method straight into the enum it works

coral star
#

You must limit yourself to what can't be mistyped. That's the entire concept of static typing

patent prawn
#

I guess that makes sense
kind of sad, now I have to rethink what I had planned

Appreciate the help!