通配符声明的非显式泛型类型的泛型返回类型 [英] Generic return type of non-explicit generic type declared by wildcard

查看:121
本文介绍了通配符声明的非显式泛型类型的泛型返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设想这段代码:

  public static< T> T [] superClassArray(Class <?extends T []> subClass){
T [] superArray =(T [])Array.newInstance(subClass.getComponentType()。getSuperclass(),0);
返回superArray;
}

返回类型 T [] 应该是任何类型的参数 subClass ,甚至认为 subClass 没有保证实际上表示 T [] ,但仅仅是一个子类(?extends T )。所以实际返回类型应该是 Object ,因为 T [] 没有比任何超类更明确地声明子类


然而,

  Integer [] objA = superClassArray(Integer []。class); 

编译是因为错误地期望返回 Integer [] 对象,但显然会抛出一个 ClassCastException ,因为实际上会返回一个 Number [] 对象。



那么是否有理由对泛型类型处理不当,只能通过相当模糊的通配符来声明,或者在我考虑的任何时候误认为

? >

解决方案

据我所知,您在尝试做的事情并不一致。
用你的方法创建你的类的SUPERTYPE数组,实际上是成功的。


但是,您正尝试将它分配给对SUBTYPE非法的引用。如果您确实确信此数组不能包含除Integer之外的任何其他类型的值,您可以明确地强制转换它:

  Integer [] objA =(Integer [])superClassArray(Integer []。class); 

但是在代码和现实世界中没有任何价值你有一个任务,你试图用这样的东西来解决,你应该再仔细考虑几次,并提出一个更好的解决方案。 :)

Imagine this piece of code:

public static <T> T[] superClassArray(Class<? extends T[]> subClass) {
    T[] superArray = (T[]) Array.newInstance(subClass.getComponentType().getSuperclass(), 0);
    return superArray;
}

The return type T[] of this method would be of whatever type was given as argument subClass, even thought subClassis not garanted to actually represent T[] but just a subclass (? extends T). So the actual return type should be Object since T[] is not declared more explicitly than being any superclass of subclass.
However,

Integer[] objA = superClassArray(Integer[].class);

compiles because it is erroneously expected to return a Integer[] object but obviously throws a ClassCastException because a Number[] object is actually returned.

So is there a justification for poor handling of generic types only declared through rather vague wildcards, or am I mistaken at any point of my consideration?

解决方案

As far as I understand, you are not very consistent in what you are trying to do. With your method you are creating an array of SUPERTYPE of your class, which actually succeds.

But then you are trying to assign it to a reference to a SUBTYPE which is illegal. If you are actually sure that this array cannot contain values of any other type than Integer you can explicitly cast it:

Integer[] objA = (Integer[]) superClassArray(Integer[].class);

BUT I don't see any value at all in a code like that and in the real world if you have a task that you are trying to solve with something like this, you sould really think about it a few more times and come up with a better solution. :)

这篇关于通配符声明的非显式泛型类型的泛型返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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