gpt4 book ai didi

java - 在 Java 字段中存储类泛型

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:06:03 25 4
gpt4 key购买 nike

有什么方法可以将构造时传入的泛型参数类型存储到参数中。我的目标:

class generic<T> {
Class<T> type;
public generic() {
super();
this.type = //Something that gets class from T
}
}

我目前正在做的是:

class generic<T> {
Class<T> type;
public generic(Class<T> type) {
super();
this.type = type;
}
}

必须两次指定类似乎很愚蠢,但我不确定还能怎么做。我认为这可能通过反射(reflection)成为可能,但我还没有对此进行调查。有没有更直接的方法?如果不是(顺便说一句)为什么会丢失信息?

最佳答案

因为 Java 泛型是用 Type Erasure 实现的

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

关于java - 在 Java 字段中存储类泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/911483/

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