Java 中的 void f(Class c) 和 void f(Class<?> c) 有区别吗?

Is there any difference between void f(Class c) and void f(Class<?> c) in Java?

无法编译以下 Java 代码并出现错误:名称冲突

class Test {

    public void f(Class<?> c) {
    }

    public void f(Class c) {
    }
}

void f(Class c)和Java中的voidf(Class<?> c)有区别吗?

在同一个 class 中声明,它们是等效的,会导致编译错误。

来自Java Language Specification

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

其中

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

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.

粗体字是这里的问题所在。

擦除Class<?>Class

Is there any difference between void f(Class c) and void f(Class c) in Java?

从来电者的角度来看,不。在方法体内,是的。在第一种情况下,参数具有 raw type Class。在第二种情况下,参数具有参数化类型 Class<?>.

实际上 ? 是一个可以与参数化 classes/interfaces 一起使用的通配符。例如 Collection<Object> 是一个通用集合,它包含 Object 类型的项目,而 Collection<?> 是所有类型集合的超类型。