Search code examples
javatype-erasure

Find the class of the generic object


Suppose I have the following class.

public class gen<T> {
   public gen(){
   }
   Class<T> class(){
      //something that figures out what T is.
   }
}

How can I implement the class() function without pass any additional information?

What I did is here, but I have to pass a object of T into the object gen.

public class gen<T> {
   public gen(){
   }
   Class<T> class(T var){
    return (Class<T>) var.getClass();
  }
}

Solution

  • It is indeed possible to do this using a fair amount of reflection. This link:

    http://www.artima.com/weblogs/viewpost.jsp?thread=208860

    Has a pretty good discussion of how to do it. It's tricky, evil, and hacky, but it can be done.