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

牧云@^-^@ 提交于 2019-12-25 04:21:58

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/9940610/how-do-you-ensure-a-class-annotation-parameter-extends-an-interface-at-compile-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!