Java类型擦除:强制转换插入规则? [英] Java Type Erasure: Rules of cast insertion?
问题描述
Java 有关类型擦除的教程似乎没有详细说明编译器强制转换插入的特定规则.有人可以解释一下该教程详细介绍的导致转换的特定规则(如下所示):
The Java tutorial on type erasure doesn't seem to detail the specific rules of cast insertion by the compiler. Can someone please explain the specific rules that cause the transformation detailed by the tutorial (reproduced below):
public class Node<T> {
public T data;
public Node(T data) { this.data = data; }
public void setData(T data) {
System.out.println("Node.setData");
this.data = data;
}
}
public class MyNode extends Node<Integer> {
public MyNode(Integer data) { super(data); }
public void setData(Integer data) {
System.out.println("MyNode.setData");
super.setData(data);
}
}
MyNode mn = new MyNode(5);
Node n = (MyNode)mn; // A raw type - compiler throws an unchecked warning
n.setData("Hello");
Integer x = (String)mn.data; // Causes a ClassCastException to be thrown.
具体地说,我想知道是什么规则导致插入(MyNode)
和(String)
.何时插入演员表,以及如何选择演员表类型?
Specifically, I'm wondering what rules cause the insertion of (MyNode)
and (String)
. When is a cast inserted, and how is the type chosen for the cast?
推荐答案
-
MyNode mn = new MyNode(5);
MyNode mn = new MyNode(5);
- 将创建
MyNode
的实例,该实例将接口Node
的通用类型T
定义为Integer
- 广播:开发人员无需强制转换,编译器无需添加强制转换
- will create an instance of
MyNode
which defines the generic typeT
of interfaceNode
asInteger
- casting: no casting necessary by developer, no casts added by compiler
Node n = (MyNode)mn;
Node n = (MyNode)mn;
- 这基本上将告诉编译器忘记泛型类型
T
并完全使用接口Node
而不使用泛型,这将导致以下结果:想象将泛型类型T
视为java.lang.Object
- 广播:开发人员无需强制转换,编译器无需添加强制转换
- this will basically tell the compiler forget about the generic type
T
and use the interfaceNode
completely without generics which will have the following consequence: imagine generic typeT
to be treated asjava.lang.Object
- casting: no casting necessary by developer, no casts added by compiler
n.setData("Hello");
n.setData("Hello");
- 将允许您添加任何种类的ob对象,因为T被视为Object(
String
,Integer
,数组,其他任何对象) - 广播:开发人员无需强制转换,编译器无需添加强制转换
- will allow you to add any kind ob object because T is treated as Object (
String
,Integer
, array, anything else) - casting: no casting necessary by developer, no casts added by compiler
Integer x = mn.data;
Integer x = mn.data;
-
nm.data
应该返回Integer
类型,因为Integer
在MyNode
类中定义为通用类型参数T
- 但是,因为使用的原始类型允许您添加
String
,所以nm.data
保留了String
实例 - 广播:开发人员无需强制转换,但是编译器会为您在后台为Integer添加强制转换,并且由于类型不匹配,您将获得
ClassCastException
nm.data
should return anInteger
type asInteger
is defined as generic type argumentT
in theMyNode
class- however because you used raw types which allowed you to add a
String
instead, thenm.data
holds aString
instance - casting: no casting necessary by developer, however the compiler will add casts to Integer behind the scenes for you and because of type mismatch, you will get the
ClassCastException
这篇关于Java类型擦除:强制转换插入规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!