3

I have this interface:

public interface IDbTable extends Serializable { public int getId(); } 

I need to obligate all the classes that implements IDbTable, to have an annotation "@DatabaseTable" and at least one field inside class that have "@DatabaseField". The only way of implementing IDbTable needs to be like this:

@DatabaseTable(tableName = "Something") public static class TestTable implements IDbTable { @DatabaseField public int id; public int getId() { return id; } } 

Is this possible with interface or inheritance? Today i have an unit test that scan all the classes and check this requirements. Is this a good practice?

3
  • Off the top of my head, the unit test approach is the best that comes to mind. Commented May 11, 2012 at 20:44
  • There is no way to make this requirements generate an error? Without having to run the unit tests? The unit test thing seems a big workaround to me Commented May 11, 2012 at 20:48
  • It is possible to check it in runtime, is it suitable for you? Commented May 11, 2012 at 20:50

2 Answers 2

2

You can't apply annotations to an interface that will be inherited by the implementing class, according to Java documentation: http://docs.oracle.com/javase/6/docs/api/java/lang/annotation/Inherited.html

Indicates that an annotation type is automatically inherited. If an Inherited meta-annotation is present on an annotation type declaration, and the user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class's superclass will automatically be queried for the annotation type. This process will be repeated until an annotation for this type is found, or the top of the class hierarchy (Object) is reached. If no superclass has an annotation for this type, then the query will indicate that the class in question has no such annotation.

Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.

Sign up to request clarification or add additional context in comments.

1 Comment

But see fusionsoft-online.com/press-releases-java-annotations.php for a library that says it allows annotation inheritance for interfaces.
0

Why don't you use annotation processing, to check that the requiered annotation is present in your class when it is sent to your framework, or at build/deployment time.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.