你如何保证类注解参数扩展在编译时的界面? [英] How do you ensure a class annotation parameter extends an interface at compile time?

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

问题描述

我有一个注释我试图定义需要一个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 将返回而不是类&LT; NoStyle&GT; 。在JLS对Java SE 5和7(找不到6,我用6)它专门说:void.class将返回类。查阅JLS类文字: http://docs.oracle.com/javase/specs/jls/se5.0/html/ex$p$pssions.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

反正在编译的时候做到这一点?如果不是我猜workround在运行时检查款式的值,以确保它延伸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天全站免登陆