您如何确保类注释参数在编译时扩展接口? [英] How do you ensure a class annotation parameter extends an interface at compile time?

查看:24
本文介绍了您如何确保类注释参数在编译时扩展接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在尝试定义的带有 Class 参数的注释.我想确保提供的类扩展了特定的接口.所以我想出了...

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".

我假设这是因为 NoStyle.class 返回的是 Class 而不是 Class.在 JLS for Java SE 5 &7(找不到 6,我正在使用 6)它特别说明void.class"将返回Class".参见 JLS 类文字:http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.8.2

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

在编译时有没有办法做到这一点?如果不是,我猜解决方法是在运行时检查 style 的值以确保它扩展 ITagStyle :'(

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 :'(

解决方案: JDeveloper 在其进程中"编译器中存在错误.检查进程外"或使用JDK7u3更正编译错误.

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) {

    }
}

已在 JDK 1.6.0_26 上测试过

This has been tested on JDK 1.6.0_26

这篇关于您如何确保类注释参数在编译时扩展接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆