Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Java在字段中存储类泛型_Java_Generics - Fatal编程技术网

用Java在字段中存储类泛型

用Java在字段中存储类泛型,java,generics,Java,Generics,有没有办法将构造时传入的泛型参数类型存储到参数中。我的目标是: class generic<T> { Class<T> type; public generic() { super(); this.type = //Something that gets class from T } } 类泛型{ 班级类型; 公共泛型(){ 超级(); this.type=//从T获取类的内容 } } 我目前正在做的是: cla

有没有办法将构造时传入的泛型参数类型存储到参数中。我的目标是:

class generic<T> {
    Class<T> type;
    public generic() {
        super();
        this.type = //Something that gets class from T
    }
}
类泛型{
班级类型;
公共泛型(){
超级();
this.type=//从T获取类的内容
}
}
我目前正在做的是:

class generic<T> {
    Class<T> type;
    public generic(Class<T> type) {
        super();
        this.type = type;
    }
}
类泛型{
班级类型;
公共泛型(类类型){
超级();
this.type=type;
}
}

必须指定两次类似乎很愚蠢,但我不确定如何执行。我认为这可能与反思有关,但我还没有对此进行调查。有没有更直接的方法?如果没有(顺便说一下)为什么会丢失信息?

我认为您不能这样做是因为。

因为Java泛型是用

在实例化泛型类型时, 编译器通过 一种称为类型擦除的技术-a 编译器删除所有 与类型参数相关的信息 和类或类中的类型参数 方法。类型擦除支持Java 使用泛型的应用程序 保持与的二进制兼容性 Java库和应用程序 是在泛型之前创建的


它们的类型不会在运行时保留,因此不能将其作为参数。java中的泛型严格来说是一个编译时概念(出于向后兼容的原因)。这就是所谓的


类对象采用类型参数的原因之一正是为了解决这个问题,因此您可以采用类对象以编程方式表示类型。

如果使用带有类型推断的静态创建方法而不是构造函数,则不需要指定两次类型

final class Generic<T> {
    private final Class<T> type;
    private Generic(Class<T> type) {
        super();
        if (type == null) {
            throw new NullPointerException();
        }
        this.type = type;
    }
    public static <T> Generic<T> newInstance(Class<T> clazz) {
        return new Generic<T>(clazz);
    }
}
...
    someFunction(Generic.newInstance(SomeType.class));
final类泛型{
私有最终类类型;
私有泛型(类类型){
超级();
if(type==null){
抛出新的NullPointerException();
}
this.type=type;
}
公共静态泛型newInstance(类clazz){
返回新的通用(clazz);
}
}
...
someFunction(Generic.newInstance(SomeType.class));

当然,如果您想将结果存储在变量中,可能还是要重复该类型

如果您使用的是泛型,为什么需要这个类?这有一种奇怪的味道。同意,您不需要在运行时访问泛型参数,因为泛型只是一种编译类型的功能。。。