简体   繁体   English

Java generics - 桥接法

[英]Java generics - bridge method

When comes to bridge method, i do know that java compiler will add them if there's a need so that overriding can be done properly by the subclass (after reading SCJP by mughal and angelikalanger website).当谈到桥接方法时,我知道 java 编译器会在需要时添加它们,以便子类可以正确完成覆盖(在 mughal 和 angelikalanger 网站阅读 SCJP 之后)。 But this is a bit confusing as per below:但这有点令人困惑,如下所示:

Before erasure:擦除前:

class x <T> {  
   void set(T t){}  
}

class y <E> extends x {  
   void set(E e) {} // name clash here  
}

class z<E> extends x {  
   void set(Object y) {} // no name clash here  
}

class z1<E> extends x<T> {  
   void set(Object y) {} // name clash here  
}

after erasure:擦除后:

class x {  
   void set (Object t) {}  
}

I understand the name clash for class y but why there is no name clash for class z?我了解 class y 的名称冲突,但为什么 class z 没有名称冲突? Also there is a name clash for class z1? class z1 也存在名称冲突? Puzzling令人费解

class y <E> extends x {  
   void set(E e) {} // name clash here  
}

Here name clash occurs because E is not a subclass of T. So you cannot override the set method this way.see the explanation for z1 to understand better.这里发生名称冲突是因为 E 不是 T 的子类。因此您不能以这种方式覆盖 set 方法。请参阅 z1 的解释以更好地理解。 For class y to work, you must have要使 class y 工作,您必须有

class y <E> extends x<E> {  
   void set(E e) {}  
}

Next:下一个:

class z<E> extends x {  
   void set(Object y) {} // no name clash here  
}

Here there is no name clash because in the class X, set method gets interpreted as这里没有名称冲突,因为在 class X 中,set 方法被解释为

void set(java.lang.Object) 

and in class z also the parameter of set is java.lang.Object.so no clash.在 class z 中,set 的参数也是 java.lang.Object.so 没有冲突。

Next:下一个:

class z1<E> extends x<T> {  
   void set(Object y) {} // name clash here  
}

Again here name clash occurs because you have to have as parameter of set whatever type parameter you give to x.这里再次发生名称冲突,因为您必须将任何类型参数作为参数设置给 x。 here, you pass to x type parameter T, but you have parameter of set method as java.lang.Object.在这里,您传递给 x 类型参数 T,但您有设置方法的参数为 java.lang.Object。 hence name clash.因此名称冲突。

For z to work you must have:要使 z 工作,您必须具备:

class z1<E> extends x<Object> {  
       void set(Object y) {}  
}

As you say, after erasure the set method takes an Object.正如您所说,擦除后设置方法采用 Object。 z extends the non-generic, after erasure x z在擦除x之后扩展非泛型

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

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