简体   繁体   English

通用和强制转换Java规则

[英]Generic and casting java rules

i have read some generic restrictions 我已经阅读了一些通用限制

when it comes to casting, it said that we cannot use cast with parameterized types 说到类型转换,它说我们不能对参数化类型使用类型转换

could anyone explain in what situation we are allowed to cast Object data type to its subclass since generic performs the cast automatically if necessary? 谁能解释在什么情况下我们可以将Object数据类型强制转换为其子类,因为在必要时泛型会自动执行强制转换?

suppose i have the following code: 假设我有以下代码:

T[] arrayVar =(T[]) new Object[1] // it causes a compiler warning but still okay T[] arrayVar =(T[]) new Object[1] //会引发编译器警告,但仍然可以

why should i use cast in this situation? 在这种情况下为什么要使用演员表? doesnt it say that in generic, cast will be done automatically? 它不是说泛型转换将自动完成吗?

Assuming T is not defined as <T extends NotObject> , then 假设T未定义为<T extends NotObject> ,则

T[] arrayVar =(T[]) new Object[1]// it causes a compiler warning but still okay

post erasure is 擦除后为

Object[] arrayVar = (Object[]) new Object[1];

which has a redundant unchecked cast. 具有多余的未经检查的演员表。

This is not type-safe. 这不是类型安全的。

Consider what happens when you do 考虑当你做的时候会发生什么

f(arrayVar)

where 哪里

void f(Object[] out) { out[0] = "A string"; }

If that can happen when String is not a subclass of T then you have a type-safety violation. 如果在String不是T的子类时发生这种情况,则说明您存在类型安全冲突。


To solve this problem you can try and create an array of a more specific type. 要解决此问题,您可以尝试创建更特定类型的数组。 If you can take a parameter of type 如果可以采用类型的参数

Class<T> clazz

then you can create your array thus 然后您可以创建数组

T[] varArray = (T[]) Array.newInstance(clazz, 1);

which is more type-safe because trying to do 这是更类型安全的,因为尝试这样做

out[0] = "";

on a Number[] for example will result in an ArrayStoreException at runtime. 例如,对Number[]进行操作将在运行时导致ArrayStoreException

It isn't perfectly (dynamically) type-safe, because T might be a type like List<String> and you can still put a List<Number> in a List[] without an ArrayStoreException . 它不是完全(动态)类型安全的,因为T可能是类似List<String>的类型,并且您仍然可以将List<Number>放入List[]而无需使用ArrayStoreException

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

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