简体   繁体   中英

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? 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. 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. 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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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