开发者

Can I make a generic interface for classes that have a specific annotation?

开发者 https://www.devze.com 2023-02-18 19:29 出处:网络
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.

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

public class Subscription { ... }

@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.


It is not possible with standart Java, but you can use AspectJ Inter-type declarations.

For example this aspect, would add the WhatEverInterface and the implmentation to every class anntotated with @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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号