Java:允许带有自定义注释的对象的集合
我想用 @MyEntity 注释来注释一些类
public @interface MyEntity {}
@MyEntity
public class MyClass { ... }
,并定义一个集合,其中只允许具有该注释的类(无需将它们定义为 public class MyClass Implements XXX
):
List<MyEntity> list = new ArrayList<MyEntity>();
list.add(new MyClass())
上面的代码导致编译错误“ArrayList 类型中的方法 add(MyEntity) 不适用于参数 (MyClass)”。有没有办法定义一个集合,只允许具有给定注释的对象?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简短的回答是否定的。
您的问题是
List
定义了 MyEntity 或其子类的列表(即,如果我们有@interface AnotherEntity extends MyEntity
那么我们可以放置AnotherEntity 到此列表)。
类
MyClass
不扩展/实现MyEntity
,它是用它注释的。即使有可能,效率也不会很高。您不知道哪些方法或字段可用,
MyEntity
不描述对象的接口。因此,它唯一的用途就是过滤错误的插入。您可以轻松地实现它,提供您的 List 实现: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 MyEntity
then we could putAnotherEntity
to this list).Class
MyClass
doesn'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,
MyEntity
doesn'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:不要认为这是可能的。为什么不让他们实现一个无方法接口呢?
Don't think this is possible. Why not have them implement a no-method interface instead?
注解的存在不会修改带注解的类的类型。
您可以创建一个仅包含用您的注释注释的元素的集合。您需要为集合创建一个包装类,该类使用反射来检查插入时注释是否存在。
它仍然无法让您进行编译时类型检查。为此,您需要一些直接影响可插入项目类型(接口或超类等)的东西
The presence of an annotation doesn't modify the annotated class's type.
You could create a collection that only contains elements which are annotated with your annotation. You would need to make a wrapper class for the collection that uses reflection to check for the presence of the annotation on insertion.
It still won't get you compile-time type checking. For that you would need something which directly affects the insertable items' type (interface or superclass, etc.)
只需重写 list: add、addAll 和构造函数的方法即可过滤具有预期注释的类。
Just override methods of list: add, addAll and constructors, to filter classes that have expected annotation.