javaobjectgenericstype-parameterinstancetype

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;
    }
}

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.