这是类型擦除的结果。在字节码级别,泛型签名只是方法的一个附加属性,不用于 JVM 的方法分派。实际的字节码级签名源自类型变量绑定的第一种类型,例如,对于类型变量T extends Number&Serializable
,原始签名的替代T
将是Number
。
为了您的声明,
public interface BaseService<T, ID> {
T findOne(ID id);
}
T
并ID
替换为Object
; 该方法的擦除签名是Object findOne(Object)
.
对于子类型声明
public class BaseServiceImpl<T,ID extends Serializable> implements BaseService<T, ID> {
@Override
public T findOne(ID id) {
return null;
}
}
the erased type of ID extends Serializable
is Serializable
, which causes the implementation method to have the erased signature Object findOne(Serializable)
.
To ensure that code using the interface BaseService
, calling the method Object findOne(Object)
, will find the implementation method, the compiler generates a bridge method having the signature Object findOne(Object)
and consisting of a plain delegation to Object findOne(Serializable)
, performing type casts where necessary.
You can identify the bridge method by calling isBridge()
on the Method
instance.
You can also use the knowledge of how the type erasure works to influence the result. By changing the declaration to
public class BaseServiceImpl<T, ID extends Object&Serializable>
implements BaseService<T, ID> {
@Override
public T findOne(ID id) {
return null;
}
}
there is no semantic difference regarding the generic type system, but the erasure of ID extends Object&Serializable
will be Object
, hence, the resulting erasure of the findOne
method will be identical to the erasure of the interface method, therefore, no bridge method will be needed in this case.