简体   繁体   English

将Java对象的实例类型传递给通用类类型参数

[英]Java Pass instance type of Object to generic class type parameter

Is it possible to pass an Objects instance type as the type parameter of a generic? 是否可以将Objects实例类型作为泛型的类型参数传递? Something like the following: 类似于以下内容:

Object obj = new Double(3.14); //Instance type Double

//Could I do the following?
Item<obj.getInstanceType()> item = new Item<obj.getInstanceType()>(obj);

public class Item<T> {
    private T item;
    public Item(T item) {
        this.item = item
    }
    public T getItem() {
        return this.item;
    }
}

No.. generic type should be known at compile time. 编号。泛型类型应在编译时知道。

Generics are there to catch possible runtime exceptions at compile time itself. 泛型在那里可以在编译时本身捕获可能的运行时异常。

List<Integer> list = new ArrayList<Integer>();
//..some code
String s = list.get(0); // this generates compilation error

because compiler knows that list is meant to store only Integer objects and assigning the value got from list to String is definitely an error. 因为编译器知道list仅用于存储Integer对象,并且将从list获得的值分配给String绝对是错误的。 If the generic type was determined at run-time this would have been difficult. 如果泛型类型是在运行时确定的,那将是困难的。

The reason generics exist in Java is so that more errors can be caught at compile time. Java中存在泛型的原因是,以便在编译时可以捕获更多错误。 It's for this reason that types NEED to be defined strongly at compile time, or else they are useless. 因此,需要在编译时强烈定义类型,否则它们将无用。

Here's for a really good learning experience on Generics: http://docs.oracle.com/javase/tutorial/java/generics/ 这是一个关于泛型的非常好的学习经验: http : //docs.oracle.com/javase/tutorial/java/generics/

泛型是在编译时解析的,因此将无法正常工作(编译器将需要执行该代码才能知道结果,并且显然不可能,因为它仍在编译:P)。

What's the point of what you're doing? 你在做什么的重点是什么? What are you trying to accomplish? 你想达到什么目的? Why not just do this: 为什么不这样做:

Item<Object> item = new Item<Object>(obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM