I’d like to annotate some classes with a @MyEntity annotation
public @interface MyEntity {}
@MyEntity
public class MyClass { ... }
And define a collection where only classes with that annotation are allowed (with no need to define them as public class MyClass implements XXX):
List<MyEntity> list = new ArrayList<MyEntity>();
list.add(new MyClass())
The above code results in a complation error “The method add(MyEntity) in the type ArrayList is not applicable for the arguments (MyClass)”. Is there a way to define a collection that only allows objects with a given annotation?
The short answer is no.
Your problem is that
List<MyEntity>defines a list of MyEntity’s or its subclasses (i.e. if we have@interface AnotherEntity extends MyEntitythen we could putAnotherEntityto this list).Class
MyClassdoesn’t extend/implementMyEntity, it’s annotated with it.Even if it was possible, it wouldn’t be efficient. You wouldn’t know which methods or fields are available,
MyEntitydoesn’t describe your object’s interface. So, the only thing it could be used for is filtering wrong insertions. You can implement it easily providing your List implementation: