简体   繁体   English

Java类类作为泛型无法正常工作

[英]Java Class class as a generic doesn't work as expected

A simple question about Class and its generic semantics. 关于类及其泛型语义的一个简单问题。 Why doesn't the following code work? 为什么以下代码不起作用?

Class<Serializable> s = String.class;

Java tells me that Class<Serializable> and Class<String> are incompatible. Java告诉我Class<Serializable>Class<String>不兼容。 How can they be, when String is implementing Serializable ? String实现Serializable时,它们怎么可能?

Shouldn't generics allow exactly this type of things? 泛型不应该完全允许这种类型的事情吗?

No, generics explicitly don't allow this kind of thing. 不,泛型明确不允许这种事情。 The classic example is a collection class of some kind. 经典示例是某种收集类。 If ArrayList<String> was a subclass of ArrayList<Serializable> , then you could write 如果ArrayList<String>ArrayList<Serializable>的子类,则可以编写

ArrayList<String> astr = new ArrayList<String>();
ArrayList<Serializable> aser = astr;
aser.add(new Integer());
// This will throw ClassCastException!
String str = astr.get(0);

After this code, you have an ArrayList<String>() containing an Integer object -- clearly this is not good. 在此代码之后,您将拥有一个包含Integer对象的ArrayList <String>()-显然这不好。

because Class<String> is not Class<Serializable> . 因为Class<String>不是Class<Serializable> However Class<String> is Class<? extends Serializable> 但是Class<String>Class<? extends Serializable> Class<? extends Serializable>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM