简体   繁体   中英

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
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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM