Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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;
    }
}
share|improve this question

4 Answers 4

up vote 5 down vote accepted

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.

share|improve this answer
1  
+1 - The only correct answer. (Yes, type information is erased, so you can't normally find out what type T is bound to. But even if that were not the case, you still couldn't "instantiate" a generic type with a parameter class that is a runtime value. That would make static typing of generics impossible.) – Stephen C Jun 12 '13 at 16:32

Generics are resolved on compilation time so that would not work (the compiler would need to execute that code to know the result, and that obviously is not possible as it is still compiling :P).

share|improve this answer

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/

share|improve this answer

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.