gpt4 book ai didi

java - 使用类参数时,类型绑定(bind)不是通过构造函数推断的吗?

转载 作者:行者123 更新时间:2023-12-02 00:10:19 24 4
gpt4 key购买 nike

尝试理解为什么 Java 在使用 Class 参数传入类型信息时在推断类型和检查类型边界方面表现不同。

以此代码为例:

public class TypeTest<T extends Number> {
Class<T> type;

TypeTest(Class<T> type) { this.type = type; }

static <S extends Number> void sMethod(Class<S> type) {}

<S extends Number> void method(Class<S> type) {}


public static void main(String[] args) throws InstantiationException, IllegalAccessException {
// 1.
TypeTest<Integer> obj = new TypeTest(Object.class); // compiles, unchecked call and assignment warnings

// 2.
obj.method(Object.class); // compile-time error, S not within bound

TypeTest obj1 = new TypeTest(Object.class); // compiles, unchecked call and assignment warnings

// 3.
obj1.method(Object.class); // compiles, unchecked call warning .

// 4.
TypeTest.sMethod(Object.class); // compile time error, Object not within bounds

// 5.
new TypeTest<Object>(Object.class); // compile time error, Object not within bounds
}

}

使用静态方法(4.),我们不能传入任何不是数字的东西,这似乎是在所提供的范围内最自然的行为。

但是,对于构造函数(1.、5.),我们必须显式指定类型参数才能获得与 4 相同的行为。否则,似乎不会从 Object.class 变量自动推断出 T 类型参数值。

构造函数和静态方法的这种差异从何而来?

另一个我完全不明白的情况是2.和3.之间的区别。为什么相同的操作编译或不编译仅取决于TypeTest对象的构造方式,而类类型参数T没有任何关系到方法类型参数S?

最佳答案

当您省略泛型类型的类型参数时 - 也就是说,每当您键入 TypeTest 时没有<Something> -- Java 忽略对该类型的所有通用检查。

参见http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html了解详情。

关于java - 使用类参数时,类型绑定(bind)不是通过构造函数推断的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12960002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com