Question

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;
    }
}
Was it helpful?

Solution

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.

OTHER TIPS

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/

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).

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top