本文介绍了当名义类需要访问修改时,无法使用交集类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
接口:
interface PublicCloneable {
Object clone();
}
interface HasPosition {
// doesn't matter
}
尝试使用交叉点类型:
@SuppressWarnings("unchecked")
<E extends PublicCloneable & HasPosition> E cloneAndIncrementPosition(E elem) {
final E clone = (E)elem.clone();
// rest omitted
}
尝试使用<$ c $进行编译c> javac 1.8.0_60 :
$ javac xx.java
xx.java:13: error: clone() in Object cannot implement clone() in PublicCloneable
<E extends PublicCloneable & HasPosition> E cloneAndIncrementPosition(E elem) {
^
attempting to assign weaker access privileges; was public
xx.java:14: error: clone() has protected access in Object
final E clone = (E)elem.clone();
^
2 errors
为什么这个交集类型对javac无效?
Why this intersection type is invalid for javac?
推荐答案
这看起来像是一个javac bug。
This looks like a javac bug.
如果Ck是Object,则会产生一个名义界面...直接超接口T1',...,Tn'
If Ck is Object, a notional interface is induced ... has direct superinterfaces T1', ..., Tn'
因此,对于 PublicCloneable& HasPosition
,引入了一个名义界面,扩展了它们,这应该没问题。
Therefore, for PublicCloneable & HasPosition
, a notional interface is introduced, extending both of them, which should be OK.
这篇关于当名义类需要访问修改时,无法使用交集类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!