java泛型界限类型

前端之家收集整理的这篇文章主要介绍了java泛型界限类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下两个签名是否相同?
public static <T> void work(Class<T> type,T instance);

public static <T,S extends T> void work(Class<T> type,S instance);

解决方法

不,这两个签名是不一样的.从 Java Language Spec,Chapter 8

Two methods have the same signature if they have the same name and argument types.

Two method or constructor declarations M and N have the same argument types if all of the following conditions hold:

  • They have the same number of formal parameters (possibly zero)
  • They have the same number of type parameters (possibly zero)

由于您的两种方法不共享相同数量的类型参数,因此签名不一样.

在使用隐式类型参数调用方法的实际情况下,它们可能被视为可互换的.但是这只是在源代码级别,从不在二进制级别.换句话说,如果您在类Foo中有一个类型参数版本的work(),并且它由类Bar中的方法调用,然后切换到work()的两个类型参数版本并重新编译唔,你还需要重新编译吧.

编辑

@onepotato问:

If they don’t have the same signatures,then why when I copy and paste them in one class Eclipse tell me that they have the same method signature?

两个签名之间存在差异,两个签名相冲突(为“超越等效”).两个签名冲突,如果一个是另一个的子签名.稍后将在同一节中解释:

Two method signatures m1 and m2 are override-equivalent iff either m1 is a subsignature of m2 or m2 is a subsignature of m1.

It is a compile-time error to declare two methods with override-equivalent signatures in a class.

The signature of a method m1 is a subsignature of the signature of a method m2 if either:

  • m2 has the same signature as m1,or
  • the signature of m1 is the same as the erasure (§4.6) of the signature of m2.
原文链接:https://www.f2er.com/java/123653.html

猜你在找的Java相关文章