简体   繁体   English

通用并在java中强制转换

[英]Generic and cast in java

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

E[] arrayVar = (E[])new Object[1];// It causes a compiler warning 

the question is, in what situation when the code will cause a run time error, 问题是,在什么情况下代码会导致运行时错误,

That code will only cause a runtime error if you try to assign the result to the reified type of E : 如果您尝试将结果分配给E的具体类型,那么该代码只会导致运行时错误:

createArray(); // no exception
String[] arr = createArray(); // causes ClassCastException

public static <E> E[] createArray() {
    return (E[]) new Object[1];
}

The safe way to create generic arrays is with the use of Array.newInstance : 创建泛型数组的安全方法是使用Array.newInstance

public static <E> E[] createArray(Class<E> component) {
    return (E[]) Array.newInstance(component, 1);
}

This method will not cause a ClassCastException . 此方法不会导致ClassCastException

to expand LastStar007's Answer 扩展LastStar007的答案

The problem with that statement is that java cannot determine the type of object E until runtime. 该语句的问题在于java直到运行时才能确定对象E的类型。 also unfortunately, java does not provide a simple way to determine the type of a specified object (getClass() does not work for this). 还不幸的是,java没有提供一种简单的方法来确定指定对象的类型(getClass()不适用于此)。

your best bet (if it is numerical data) would be to check against the maximum of each mnemonic or for character data, check against the storage size per a character. 您最好的选择(如果是数字数据)将检查每个助记符或字符数据的最大值,检查每个字符的存储大小。 yes it sounds tedious, but java has no typeinfo, like C++ which would make things a lot easier 是的,这听起来很乏味,但java没有typeinfo,比如C ++会让事情变得更容易

It will never cause a run-time error because it will always cause a compile-time error. 它永远不会导致运行时错误,因为它总是会导致编译时错误。 An Object cannot be down-cast to an E , and therefore an Object[] cannot be down-cast to an E[] . 无法将Object转码为E ,因此无法将Object[]转发为E[] Beyond that, you can't create an array of type E because the class has no idea what the type of E is at compile-time. 除此之外,您无法创建E类型的数组,因为类在编译时不知道E的类型是什么。

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

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