7

具有以下定义:

public interface BaseService<T, ID> {

    T findOne(ID id);

}

public class BaseServiceImpl<T,ID extends Serializable> implements BaseService<T, ID> {

    @Override
    public T findOne(ID id) {
        return null;
    }

}

为什么BaseServiceImpl.class.getDeclaredMethods()返回2个方法:

  • public java.lang.Object BaseServiceImpl.findOne(java.io.Serializable)
  • public java.lang.Object BaseServiceImpl.findOne(java.lang.Object)

有没有办法过滤掉这些?

4

1 回答 1

5

这是类型擦除的结果。在字节码级别,泛型签名只是方法的一个附加属性,不用于 JVM 的方法分派。实际的字节码级签名源自类型变量绑定的第一种类型,例如,对于类型变量T extends Number&Serializable,原始签名的替代T将是Number

为了您的声明,

public interface BaseService<T, ID> {
    T findOne(ID id);
}

TID替换为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.

于 2017-05-22T18:32:22.420 回答