gpt4 book ai didi

Java泛型——类型推导

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:24 26 4
gpt4 key购买 nike

考虑以下几点:

 public class GenericTest {
static void print(int x) {
System.out.println("Int: " + x);
}
static void print(String x) {
System.out.println("String: " + x);
}

static void print(Object x) {
System.out.println("Object: " + x);
}

static <T> void printWithClass(T t) {
print(t);
}
public static void main(String argsp[]) {
printWithClass("abc");
}
}

它打印对象:abc。为什么不打印 String: abc?

最佳答案

这是因为 Java type erasure : 你的

static <T> void printWithClass(T t) {
print(t);
}

实际上是

之上的语法糖
static void printWithClass(Object t) {
print(t);
}

公平地说,“语法糖”让编译器可以做一些非常好的和重要的检查,但在运行时只有一个 printWithClass 方法的副本,它使用 java.lang.Object 作为变量 t 的类型。

如果您体验过其他语言(C#、C++ 模板、Ada)中的泛型,类型删除可能与您所知道的相反,但这就是它在幕后的工作方式。

关于Java泛型——类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9312978/

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