如何用有效的泛型声明Class.class [英] how to declare Class.class with valid generics

查看:115
本文介绍了如何用有效的泛型声明Class.class的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想知道是否有方法来声明 Class Class 具有有效类型参数的对象:

  Class cc1 = Class.class; //原始类型
Class< Class> cc2 = Class.class; //现在参数是原始类型
Class< Class<>> cc3 = Class.class; //编译错误:不可兑换类型

如果 Class Class <?> 是可以互换的,为什么 Class< Class> Class< ; Class<>> not?



编辑:这个问题可以概括为嵌套的原始类型参数。例如:

  ArrayList< ArrayList<>> lst = new ArrayList< ArrayList>(); //相同的编译错误

EDIT2:我应该改写一下这个问题:我知道

  Class<?> c = Class.class; 

是有效的,但我想知道为什么 Class< Class> Class >

不同

解决方案

泛型有一些非常严重的限制。在这种情况下,您不能将类型分配给 Class< Class> 的内部类型,因为您实际上引用了原始类型,而不是原始类型的实现。它会给你一个警告,但你无法解决这个警告。



Class< Class<>> 本身并不是不可转换的类型,因为它没有类型 Class< Class< T>>< / $ c,所以你不能直接指定类$ c>,它有类型 Class< T>



想想另一种方式;试试列表< List< String>> 。要创建它,你需要创建一个带有字符串列表的List。这是可行的,因为列表可以包含列表。



类更像是一个原始数据对象,所以我不认为有可能创建一个类这是类别的其他类型。

编辑:关于 ArrayList< ArrayList<> > 是您对 Class< Class<>> 的不可转换类型问题的一个更明显的例子。


Note: purely out of curiosity and not for any actual use case.

I'm wondering if there is a way to declare the Class Class object with valid type parameters:

Class cc1 = Class.class; //raw type
Class<Class> cc2 = Class.class; //now parameter is raw type
Class<Class<?>> cc3 = Class.class; //compile error: inconvertible types

If Class and Class<?> are interchangeable, why are Class<Class> and Class<Class<?>> not?

EDIT: the question can be generalized to an issue of nested raw type parameters. For example:

ArrayList<ArrayList<?>> lst = new ArrayList<ArrayList>(); //same compile error

EDIT2: I should rephrase the question a little: I know that

Class<?> c = Class.class;

is valid but I'm wondering why Class<Class> is not the same as Class<Class<?>>

解决方案

Generics have some pretty serious limitations. In this case you can't assign a type to the inner type of Class<Class> because you're actually referencing the raw type, not an implementation of the raw type. It will give you a warning, but you have no way to fix that warning.

Class<Class<?>> by itself isn't an inconvertible type, you just can't assign a class directly to it because it doesn't have the type Class<Class<T>>, it has the type Class<T>.

Think of it another way; try List<List<String>>. To create that, you need to create a List that takes a List of Strings. This works because lists can contain lists.

A Class is more like a primitive than a data object, so I don't think it'd be possible to create a Class that is of type Class of something else.

Edit: your extra question about ArrayList<ArrayList<?>> is a more obvious example of the inconvertible type issue you're having with Class<Class<?>>.

这篇关于如何用有效的泛型声明Class.class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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