开发者

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


You can't figure out the runtime value of T. This is due to type erasure.


No. The bytecodes for the compiled version of your class do not retain enough information to determine T, because of type erasure. What you've done with passing in an actual object of type T is about the best you can do.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜