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

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

问题描述

我想用泛型和可变参数实现一个函数.

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
    }
}

这里的目的是断言传递给这个函数的所有参数都是类对象,扩展了作为第一个参数给出的类.所以 main 方法的前两行会编译,第三行会产生错误.

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?

附加问题: 如何重新设计它以防止在调用doNastyThingsToClasses"函数的每一行上显示此警告?我可以将它更改为doNastyThingsToClasses(Class<A> parent, Class<?>... classes)"并摆脱警告,但这也删除了编译时类型检查——如果我想的话,那就不太好了确保正确使用此功能.有什么更好的解决方案吗?

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?

推荐答案

Angelika Langer 的 Java 泛型 FAQ 详细解释.(滚动到为什么当我调用varargs"方法时编译器有时会发出未经检查的警告?"- ID 不能正常工作.)

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

基本上,您最终会以比平时更糟糕的方式丢失信息.Java泛型的另一个小痛点:(

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

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

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