java中强制类型转换规则,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 {

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 {

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.

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);

will create an instance of MyNode which defines the generic type T of interface Node as Integer

casting: no casting necessary by developer, no casts added by compiler

Node n = (MyNode)mn;

this will basically tell the compiler forget about the generic type T and use the interface Node completely without generics which will have the following consequence: imagine generic type T to be treated as java.lang.Object

casting: no casting necessary by developer, no casts added by compiler

n.setData("Hello");

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;

nm.data should return an Integer type as Integer is defined as generic type argument T in the MyNode class

however because you used raw types which allowed you to add a String instead, the nm.data holds a String 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值