Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force a Java subclass to define an Annotation?

If a class defined an annotation, is it somehow possible to force its subclass to define the same annotation?

For instance, we have a simple class/subclass pair that share the @Author @interface. What I'd like to do is force each further subclass to define the same @Author annotation, preventing a RuntimeException somewhere down the road.

TestClass.java:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@interface Author { String name(); }

@Author( name = "foo" )
public abstract class TestClass
{
    public static String getInfo( Class<? extends TestClass> c )
    {
        return c.getAnnotation( Author.class ).name();
    }

    public static void main( String[] args )
    {
        System.out.println( "The test class was written by "
                        + getInfo( TestClass.class ) );
        System.out.println( "The test subclass was written by " 
                        + getInfo( TestSubClass.class ) );
    }
}

TestSubClass.java:

@Author( name = "bar" )
public abstract class TestSubClass extends TestClass {}

I know I can enumerate all annotations at runtime and check for the missing @Author, but I'd really like to do this at compile time, if possible.

like image 447
Limo Driver Avatar asked Sep 18 '08 18:09

Limo Driver


People also ask

Do subclasses inherit annotations?

Class annotations can not be inherited by subclasses, but annotations on nonprivate non-constructor member methods and fields are inherited, together with the method / field they are associated with.

How do you inherit annotations?

Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it.

How do custom annotations work in Java?

In Java, annotations are metadata about the source code. They do not have any direct effect on the execution of the Java program. Annotations in Java were introduced in JDK 5. The main purpose of using annotation is that it gives instructions to the compiler at the build-time and at the runtime of program execution.


1 Answers

You can do that with JSR 269, at compile time. See : http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api

Edit 2020-09-20: Link is dead, archived version here : https://web.archive.org/web/20150516080739/http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html

like image 59
Bouil Avatar answered Oct 20 '22 01:10

Bouil