简体   繁体   中英

How do you ensure a class annotation parameter extends an interface at compile time?

I have an annotation I'm attempting to define that takes a Class parameter. I would like to ensure that the Class provided extends a specific interface. So I came up with...

public @interface Tag {
    Class<? extends ITagStyle> style() default NoStyle.class
}
public class NoStyle implements ITagStyle {
    ...
}

However I get a compile error of "incompatible types".

I'm assuming this is because NoStyle.class is returning Class instead of Class<NoStyle> . In the JLS for Java SE 5 & 7 (couldn't find 6, I'm using 6) it specifically says that "void.class" would return "Class". SEE JLS Class literals: http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.8.2

Is there anyway to do this at compile time? If not I'm guessing the workround is to check the value of style at runtime to ensure it extends ITagStyle :'(

RESOLUTION: JDeveloper has a bug in their "in process" compiler. Checking "out of process" or using JDK7u3 corrects the compile error.

This works, so either you are missing something obvious or your error is not related to what you are showing us:

public class Test {

    public interface ITagStyle {
    }

    public @interface Tag {
        Class<? extends ITagStyle> style() default NoStyle.class;
    }

    public class NoStyle implements ITagStyle {
    }

    public class SomeStyle implements ITagStyle {

    }

    @Tag(style = SomeStyle.class)
    public static void main(String[] args) {

    }
}

This has been tested on JDK 1.6.0_26

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