1

When I have an Interface, for example:

public interface Model {

    String toString();

}

And I want that every class that implements this Interface will use the following Annotations:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)

So it will look like this in the Interface:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public interface Model {

    String toString();

}

And a test class:

@XmlRootElement(name = "user")
public class User implements Model {

}

Something like this example doesn't work. How can I perform that, an abstract class with the annotations is maybe the solution?

Thank you in advance!

nberlijn
  • 313
  • 5
  • 10
  • 1. There is NO obligation in Java that annotation must be set (if I understand, maybe no) 2. "not work" ... with which the message? 3. Annotationi, I have read somewhere, are not derived from parent. – Jacek Cz Aug 29 '15 at 13:12
  • 2
    @JacekCz I think the OP means that he wants implementations of that interface to automatically inherit those annotations, so "not work" means that those annotations didn't get inherited. – C. K. Young Aug 29 '15 at 13:17
  • 1
    First shot http://stackoverflow.com/questions/4745798/why-java-classes-do-not-inherit-annotations-from-implemented-interfaces?rq=1 (and few others) – Jacek Cz Aug 29 '15 at 13:19
  • The [Unofficial JAXB Guide](https://jaxb.java.net/guide/Mapping_interfaces.html) has a writeup on this subject with some recommendations. – Parker Aug 29 '15 at 13:24
  • @JacekCZ I updated my question with what I want to achive! – nberlijn Aug 29 '15 at 13:49

1 Answers1

2

A class never inherits annotations from the interfaces it implements. Annotations that are so designated can be inherited from superclasses, but that's a characteristic of the annotation, and not the default. If the annotations you are trying to use happen to be inheritable in that way -- you'll have to check their documentation -- then you can cause them to be inherited by deriving all your model classes from a common, annotated, superclass.

Really, though, what's so bad about annotating each class explicitly? It's clearer, and no more verbose than implementing an interface.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157