[英]Can I make a generic interface for classes that have a specific annotation?
I'd like to know if there's a way to make a generic interface which can be implemented with all of the classes that have a specific annotation on class level. 我想知道是否有一种方法可以创建一个通用接口,该接口可以在类级别具有特定注释的所有类中实现。
For example: 例如:
@XmlRootElement
@XmlRootElement
public class Subscription { ... }公共类订阅{...}
@XmlRootElement@XmlRootElement
public class Author { ... }公共类作者{...}
I'd like to make a generic interface that is applicable for these two classes (and more to come). 我想创建一个适用于这两个类的通用接口(并且以后还会更多)。 Is there a way to achieve this?
有没有办法做到这一点?
Interfaces and inheritance are used to propagate functionality "vertically", down the inheritance graph. 接口和继承用于沿继承图“垂直”传播功能。
Annotations are for additional features that can be bolted on to classes, methods and so on, and are practically unrelated to interfaces. 注释是针对可以附加到类,方法等上的附加功能,实际上与接口无关。
If you know in advance what your classes will be and how they will be related to each other, you probably don't need annotations at all. 如果您事先知道您的类是什么以及它们之间的关系,您可能根本不需要注释。 The reason for this is that you can make them implement marker interfaces (
java.io.Serializable
is an example of them), which are practically the same as class level annotations (without a parameter), except much easier to work with. 这样做的原因是,您可以使它们实现标记接口(
java.io.Serializable
是它们的一个示例),它们实际上与类级别的批注相同(没有参数),但使用起来更容易。
It is not possible with standart Java, but you can use AspectJ Inter-type declarations . 使用标准Java是不可能的,但是您可以使用AspectJ Inter-type声明 。
For example this aspect, would add the WhatEverInterface and the implmentation to every class anntotated with @XmlRootElement
. 例如,这方面将向每个以
@XmlRootElement
类添加WhatEverInterface和@XmlRootElement
。
public aspect MyAspect {
declare parents: (@XmlRootElement) implements WhatEverInterface;
public void WhatEverInterface.doSomething() {
System.out.println("something");
}
}
Its as simple as this: 就这么简单:
interface XmlProcessor
{
public void process(XmlRootElement root);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.