1 Reply Latest reply: May 23, 2011 2:12 PM by 852060 RSS

    Invalid generic methods

    863823
      I'd be interested in knowing why these two methods cannot be compiled (they're rejected for the same reason). It seems to me that it is clear at compile time that x is an instance of a class of type T, so what's the problem?
      <T> T getIt (T x) throws Exception {
        return x.getClass().newInstance();
      }
      
      <T> void doIt (T x) {
        Class<? extends T> c = x.getClass();
      }
      MC
        • 1. Re: Invalid generic methods
          852060
          Hello MC,

          please read the documentation of Object.getClass()[1] and the JLS[2]. The method is special in that it returns "Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called". The erasure of T (where T is a type variable with the implicit upper bound Object) is Object. Thus the return type of x.getClass() is Class<? extends Object>.

          With kind regards
          Ben

          [1] http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#getClass%28%29
          [2] http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#123066