Java泛型和可变参数 [英] Java generics and varargs

查看:243
本文介绍了Java泛型和可变参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  public class Question {
public静态< A> void doNastyThingsToClasses(Class< A>父类,Class<?extends A> ...类){
/ ***这里的东西*** /
}
public static class NotQuestion {
}
public static class SomeQuestion extends Question {
}
public static void main(String [] args){
doNastyThingsToClasses(Object.class,Question.class,SomeQuestion 。类); // OK
doNastyThingsToClasses(Question.class,SomeQuestion.class); // OK
doNastyThingsToClasses(Question.class,Object.class,SomeQuestion.class); //编译失败
}
}

这里的意图是断言传递给该函数的所有参数都是Class对象,扩展了作为第一个参数给出的Class。因此,main方法的第一行会编译,第三行会产生错误。



我的问题是:为什么我得到Type safety :为前面两行的varargs参数消息创建了一个类的泛型数组?

我在这里丢失了什么?



其他问题: 如何重新设计它以防止在每行调用doNastyThingsToClasses函数时显示此警告?我可以将它改为doNastyThingsToClasses(Class< A> parent,Class<>>类)并且摆脱警告,但是这也删除了编译时类型检查---如果我想要确保正确使用此功能。任何更好的解决方案?

解决方案

几乎总是如此,Angelika Langer的Java泛型常见问题详细解释它。 (滚动到为什么编译器有时会在我调用varargs方法时发出未经检查的警告? - 这个ID不起作用。)

基本上,你最终会以比平常更糟的方式丢失信息。 Java泛型中另一个小小的痛点:($ / b $ b

I'd like to implement a function with both generics and varargs.

public class Question {
    public static <A> void doNastyThingsToClasses(Class<A> parent, Class<? extends A>... classes) {
        /*** something here ***/
    }
    public static class NotQuestion {
    }
    public static class SomeQuestion extends Question {
    }
    public static void main(String[] args) {
        doNastyThingsToClasses(Object.class, Question.class, SomeQuestion.class); // OK
        doNastyThingsToClasses(Question.class, SomeQuestion.class); // OK
        doNastyThingsToClasses(Question.class, Object.class, SomeQuestion.class); // compilation failure
    }
}

The intention here is to assert that all parameters passed to this function are Class objects extending the Class given as the first parameter. So the two first lines of main method would compile and the 3rd one generates an error.

My question is: Why I get "Type safety : A generic array of Class is created for a varargs parameter" message for the first two lines?

Am I missing something here?

Additional question: how to redesign it to prevent this warning from being shown on every line calling "doNastyThingsToClasses" function? I can change it to "doNastyThingsToClasses(Class<A> parent, Class<?>... classes)" and get rid of the warnings but this also removes the compilation-time type checking --- not so good if I wanted to assure the right use of this function. Any better solution?

解决方案

As almost always, Angelika Langer's Java generics FAQ explains it in great detail. (Scroll to "Why does the compiler sometimes issue an unchecked warning when I invoke a "varargs" method?" - the ID doesn't work well.)

Basically, you end up losing information in a worse way than normal. Yet another little pain point in Java generics :(

这篇关于Java泛型和可变参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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