Java泛型读书笔记 (二)

时间:2023-03-09 02:52:17
Java泛型读书笔记 (二)

关于Java泛型擦除后,继承一个泛型类带来的问题

有如下泛型类Pair:

public class Pair<T>
{
private T second;
private T first; public Pair()
{
first = null;
second = null;
} public Pair(T first, T second)
{
this.first = first;
this.second =second;
} public T getFirst()
{
return first;
} public T getSecond()
{
return second;
} public void setFirst(T newValue)
{
first = newValue;
} public void setSecond(T newValue)
{
second = newValue;
}
}

编译器会进行类型擦除,将其变为下面的普通类:

public class Pair
{
private Object second;
private Object first; public Pair()
{
first = null;
second = null;
} public Pair(Object first, Object second)
{
this.first = first;
this.second =second;
} public Object getFirst()
{
return first;
} public Object getSecond()
{
return second;
} public void setFirst(Object newValue)
{
first = newValue;
} public void setSecond(Object newValue)
{
second = newValue;
}
}

现在,有一个继承自泛型类Pair的类DateInterval:

class DateInterval extends Pair<Date>
{
public void setSecond(Date second)
{
if (second.compareTo(getFirst()) >= 0)
super.setSecond(second);
...
}
}

这个类重写了Pair的方法setSecond, 那么在类型擦除的时候,这个类其实是继承自类Pair:

class DateInterval extends Pair
{
public void setSecond(Date second)
{
if (second.compareTo(getFirst()) >= 0)
super.setSecond(second);
...
}
}

注意,这里的setSecond方法的参数还依然是Date类型的,不会被擦除,这是因为编译器擦除类型参数的时候擦除的是泛型类所在的类型参数,这个DateInterval类不是泛型类,方法setSecond的参数Date second也不是泛型参数。

那么,如果java编译器不做任何特殊处理的话,这个本来想覆盖Pair中setSecond方法的类就变成了一个DateInterval类中的新方法了,因为两个方法的签名不同,一个是Object参数,一个是Date参数:

public class Pair
{
... public void setSecond(Object newValue)
{
second = newValue;
}
} class DateInterval extends Pair
{
public void setSecond(Date second)
{
if (second.compareTo(getFirst()) >= 0)
super.setSecond(second);
...
}
}

那么当我们想用到多态的时候:

DateInterval interval = new DateInterval(. . .);
Pair<Date> pair = interval; // OK--assignment to superclass
pair.setSecond(aDate);

像上面这样,interval向上转型为了父类Pair,那么在调用pair.setSecond的时候,应该调用pair的实际类型DateInterval中的setSecond(Date second)方法,
但由于类型擦除,DateInterval中的setSecond(Date second)方法是新方法,没有重写父类Pair中的任何方法,那么就不会启动多态机制,pair.setSecond(aDate)只会调用父类Pair中的setSecond(Object)方法。

这显然不是我们想要的,为了解决这种问题,Java编译器会在DateInterval类中加入一个桥接方法 setSecond(Object newValue) 来达到覆盖擦除类型参数后的父类Pair中同名方法的作用:

class DateInterval extends Pair
{
public void setSecond(Date second)
{
if (second.compareTo(getFirst()) >= 0)
super.setSecond(second);
...
} //编译器加入的桥接方法,使其可以实现多态,并调用正确的,上面高亮的setSecond(Date second)方法
public void setSecond(Object second)
{
setSecond((Date) second);
}
}

那么下面这段代码的执行顺序:

pair.setSecond(aDate)
  • 首先,pair引用的实际类型是DateInterval,多态机制会调用DateInterval.setSecond(Object second)

  • DateInterval.setSecond(Object second)是桥接方法,内部会调用真正的处理方法DateInterval.setSecond(Date second)

当一个继承自泛型类的类想覆盖的方法是一个get方法时,情况就更奇怪了,如下代码:

class DateInterval extends Pair<Date>
{
public Date getSecond()
{
return (Date) super.getSecond().clone();
}
...
}

这个DateInterval覆盖了父类Pair的方法getSecond,由于泛型类类参数的擦除,Pair变为了Pair,getSecond返回值也变为了Object:

public class Pair
{
...
public Object getSecond()
{
return second;
}
...
}

那么跟前面讲得情况相同,DateInterval类中原本想覆盖的方法public Date getSecond() 变为了一个DateInterval类中新定义的方法,没有了多态机制。
同样,Java会在编译的时候加入一个桥接方法:

class DateInterval extends Pair<Date>
{
public Date getSecond()
{
return (Date) super.getSecond().clone();
} //桥接方法
public Object getSecond()
{
...
}
...
}

由于真正的Java代码是不能只靠方法的返回类型不同区分一个方法的,但是Java的字节码是可以将这种情况视为两个不同的方法的,所以上面的这种Java桥接方法可以工作。

You could not write Java code like that; it would be illegal to have two methods with the same parameter types—here, with no parameters. However, in the virtual machine, the parameter types and the return type specify a method. Therefore, the compiler can produce bytecodes for two methods that differ only in their return type, and the virtual machine will handle this situation correctly.

这种方式不限于泛型类,像下面的代码:

public class Employee implements Cloneable
{
public Employee clone() throws CloneNotSupportedException { ... }
}

Employee类实现了Cloneable接口的Object clone()方法,但是它实现的是一个返回更具体类型Employee的方法,这在Java中是允许的。
而且也是通过Java在编译时加入一个同名的,返回Object类型的clone方法实现的:

public class Employee implements Cloneable
{
public Employee clone() throws CloneNotSupportedException { ... } //桥接方法,此方法的方法体是调用上面返回Employee类型的clone方法。
public Object clone() {…}
}

总结

  1. 在Java虚拟机中是没有泛型的,只有普通的类和方法
  2. 所有的类型参数都被替换到它的边界上
  3. 桥接方法是被用来保留多态机制的
  4. 编译器会在适当的地方加入强制类型转换的代码,以便达到类型安全的目的

:first-child{margin-top:0!important}img.plugin{box-shadow:0 1px 3px rgba(0,0,0,.1);border-radius:3px}iframe{border:0}figure{-webkit-margin-before:0;-webkit-margin-after:0;-webkit-margin-start:0;-webkit-margin-end:0}kbd{border:1px solid #aaa;-moz-border-radius:2px;-webkit-border-radius:2px;border-radius:2px;-moz-box-shadow:1px 2px 2px #ddd;-webkit-box-shadow:1px 2px 2px #ddd;box-shadow:1px 2px 2px #ddd;background-color:#f9f9f9;background-image:-moz-linear-gradient(top,#eee,#f9f9f9,#eee);background-image:-o-linear-gradient(top,#eee,#f9f9f9,#eee);background-image:-webkit-linear-gradient(top,#eee,#f9f9f9,#eee);background-image:linear-gradient(top,#eee,#f9f9f9,#eee);padding:1px 3px;font-family:inherit;font-size:.85em}.oembeded .oembed_photo{display:inline-block}img[data-echo]{margin:25px 0;width:100px;height:100px;background:url(../img/ajax.gif) center center no-repeat #fff}.spinner{display:inline-block;width:10px;height:10px;margin-bottom:-.1em;border:2px solid rgba(0,0,0,.5);border-top-color:transparent;border-radius:100%;-webkit-animation:spin 1s infinite linear;animation:spin 1s infinite linear}.spinner:after{content:'';display:block;width:0;height:0;position:absolute;top:-6px;left:0;border:4px solid transparent;border-bottom-color:rgba(0,0,0,.5);-webkit-transform:rotate(45deg);transform:rotate(45deg)}@-webkit-keyframes spin{to{-webkit-transform:rotate(360deg)}}@keyframes spin{to{transform:rotate(360deg)}}p.toc{margin:0!important}p.toc ul{padding-left:10px}p.toc>ul{padding:10px;margin:0 10px;display:inline-block;border:1px solid #ededed;border-radius:5px}p.toc li,p.toc ul{list-style-type:none}p.toc li{width:100%;padding:0;overflow:hidden}p.toc li a::after{content:"."}p.toc li a:before{content:"• "}p.toc h5{text-transform:uppercase}p.toc .title{float:left;padding-right:3px}p.toc .number{margin:0;float:right;padding-left:3px;background:#fff;display:none}input.task-list-item{margin-left:-1.62em}.markdown{font-family:"Hiragino Sans GB","Microsoft YaHei",STHeiti,SimSun,"Lucida Grande","Lucida Sans Unicode","Lucida Sans",'Segoe UI',AppleSDGothicNeo-Medium,'Malgun Gothic',Verdana,Tahoma,sans-serif;padding:20px}.markdown a{text-decoration:none;vertical-align:baseline}.markdown a:hover{text-decoration:underline}.markdown h1{font-size:2.2em;font-weight:700;margin:1.5em 0 1em}.markdown h2{font-size:1.8em;font-weight:700;margin:1.275em 0 .85em}.markdown h3{font-size:1.6em;font-weight:700;margin:1.125em 0 .75em}.markdown h4{font-size:1.4em;font-weight:700;margin:.99em 0 .66em}.markdown h5{font-size:1.2em;font-weight:700;margin:.855em 0 .57em}.markdown h6{font-size:1em;font-weight:700;margin:.75em 0 .5em}.markdown h1+p,.markdown h1:first-child,.markdown h2+p,.markdown h2:first-child,.markdown h3+p,.markdown h3:first-child,.markdown h4+p,.markdown h4:first-child,.markdown h5+p,.markdown h5:first-child,.markdown h6+p,.markdown h6:first-child{margin-top:0}.markdown hr{border:1px solid #ccc}.markdown p{margin:1em 0;word-wrap:break-word}.markdown ol{list-style-type:decimal}.markdown li{display:list-item;line-height:1.4em}.markdown blockquote{margin:1em 20px}.markdown blockquote>:first-child{margin-top:0}.markdown blockquote>:last-child{margin-bottom:0}.markdown blockquote cite:before{content:'\2014 \00A0'}.markdown .code{border-radius:3px;word-wrap:break-word}.markdown pre{border-radius:3px;word-wrap:break-word;border:1px solid #ccc;overflow:auto;padding:.5em}.markdown pre code{border:0;display:block}.markdown pre>code{font-family:Consolas,Inconsolata,Courier,monospace;font-weight:700;white-space:pre;margin:0}.markdown code{border-radius:3px;word-wrap:break-word;border:1px solid #ccc;padding:0 5px;margin:0 2px}.markdown img{max-width:100%}.markdown mark{color:#000;background-color:#fcf8e3}.markdown table{padding:0;border-collapse:collapse;border-spacing:0;margin-bottom:16px}.markdown table tr td,.markdown table tr th{border:1px solid #ccc;margin:0;padding:6px 13px}.markdown table tr th{font-weight:700}.markdown table tr th>:first-child{margin-top:0}.markdown table tr th>:last-child{margin-bottom:0}.markdown table tr td>:first-child{margin-top:0}.markdown table tr td>:last-child{margin-bottom:0}.MathJax_Hover_Frame{border-radius:.25em;-webkit-border-radius:.25em;-moz-border-radius:.25em;-khtml-border-radius:.25em;box-shadow:0 0 15px #83A;-webkit-box-shadow:0 0 15px #83A;-moz-box-shadow:0 0 15px #83A;-khtml-box-shadow:0 0 15px #83A;border:1px solid #A6D!important;display:inline-block;position:absolute}.MathJax_Hover_Arrow{position:absolute;width:15px;height:11px;cursor:pointer}#MathJax_About{position:fixed;left:50%;width:auto;text-align:center;border:3px outset;padding:1em 2em;background-color:#DDD;color:#000;cursor:default;font-family:message-box;font-size:120%;font-style:normal;text-indent:0;text-transform:none;line-height:normal;letter-spacing:normal;word-spacing:normal;word-wrap:normal;white-space:nowrap;float:none;z-index:201;border-radius:15px;-webkit-border-radius:15px;-moz-border-radius:15px;-khtml-border-radius:15px;box-shadow:0 10px 20px gray;-webkit-box-shadow:0 10px 20px gray;-moz-box-shadow:0 10px 20px gray;-khtml-box-shadow:0 10px 20px gray;filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true')}.MathJax_Menu{position:absolute;background-color:#fff;color:#000;width:auto;padding:5px 0;border:1px solid #CCC;margin:0;cursor:default;font:menu;text-align:left;text-indent:0;text-transform:none;line-height:normal;letter-spacing:normal;word-spacing:normal;word-wrap:normal;white-space:nowrap;float:none;z-index:201;border-radius:5px;-webkit-border-radius:5px;-moz-border-radius:5px;-khtml-border-radius:5px;box-shadow:0 10px 20px gray;-webkit-box-shadow:0 10px 20px gray;-moz-box-shadow:0 10px 20px gray;-khtml-box-shadow:0 10px 20px gray;filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true')}.MathJax_MenuItem{padding:1px 2em;background:0 0}.MathJax_MenuArrow{position:absolute;right:.5em;color:#666}.MathJax_MenuActive .MathJax_MenuArrow{color:#fff}.MathJax_MenuArrow.RTL{left:.5em;right:auto}.MathJax_MenuCheck{position:absolute;left:.7em}.MathJax_MenuCheck.RTL{right:.7em;left:auto}.MathJax_MenuRadioCheck{position:absolute;left:.7em}.MathJax_MenuRadioCheck.RTL{right:.7em;left:auto}.MathJax_MenuLabel{padding:1px 2em 3px 1.33em;font-style:italic}.MathJax_MenuRule{border-top:1px solid #DDD;margin:4px 3px}.MathJax_MenuDisabled{color:GrayText}.MathJax_MenuActive{background-color:#606872;color:#fff}.MathJax_Menu_Close{position:absolute;width:31px;height:31px;top:-15px;left:-15px}#MathJax_Zoom{position:absolute;background-color:#F0F0F0;overflow:auto;display:block;z-index:301;padding:.5em;border:1px solid #000;margin:0;font-weight:400;font-style:normal;text-align:left;text-indent:0;text-transform:none;line-height:normal;letter-spacing:normal;word-spacing:normal;word-wrap:normal;white-space:nowrap;float:none;box-shadow:5px 5px 15px #AAA;-webkit-box-shadow:5px 5px 15px #AAA;-moz-box-shadow:5px 5px 15px #AAA;-khtml-box-shadow:5px 5px 15px #AAA;filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true')}#MathJax_ZoomOverlay{position:absolute;left:0;top:0;z-index:300;display:inline-block;width:100%;height:100%;border:0;padding:0;margin:0;background-color:#fff;opacity:0;filter:alpha(opacity=0)}#MathJax_ZoomFrame{position:relative;display:inline-block;height:0;width:0}#MathJax_ZoomEventTrap{position:absolute;left:0;top:0;z-index:302;display:inline-block;border:0;padding:0;margin:0;background-color:#fff;opacity:0;filter:alpha(opacity=0)}.MathJax_Preview{color:#888}#MathJax_Message{position:fixed;left:1px;bottom:2px;background-color:#E6E6E6;border:1px solid #959595;margin:0;padding:2px 8px;z-index:102;color:#000;font-size:80%;width:auto;white-space:nowrap}#MathJax_MSIE_Frame{position:absolute;top:0;left:0;width:0;z-index:101;border:0;margin:0;padding:0}.MathJax_Error{color:#C00;font-style:italic}footer{position:fixed;font-size:.8em;text-align:right;bottom:0;margin-left:-25px;height:20px;width:100%}
-->