Filipe Carvalho
Filipe Carvalho

Reputation: 628

Can i make some annotation required in classes that implements my interface?

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?

Upvotes: 3

Views: 3941

Answers (2)

Shawn
Shawn

Reputation: 9402

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.

Upvotes: 2

miks
miks

Reputation: 544

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.

Upvotes: 0

Related Questions