Search code examples
javagenericsjls

Generic method invocation with <T>


I have a problem with understanding such generic method invocation:

object = ObjectGenerator.<T> getObject(objectName);

Here comes a context for above situation:

class GenClass<T> {

   private T object;

   // ... some code

   public void initObject(String objectName) {
      object = ObjectGenerator.<T> getObject(objectName);
   }
}

class ObjectGenerator {

   public static <T extends Object> T getObject(String name) {
      // some code
      return someObject;
   }
}

The question is what role plays <T> before getObject(objectName) invocation?


Solution

  • Note: in the specific example you have given, ObjectGenerator.getObject(objectName); should compile fine.

    In some situations, the type inference mechanism can't resolve the fact that in:

    T object;
    object = ObjectGenerator.getObject(objectName);
    

    the returned type should be T. In such a case, you need give the compiler a little help by explicitly indicating the return type you expect.

    Here is a contrived example where you need to explicitly specify the generic type:

    class Example {
        public static <T> List<T> m1() {
            return m2(Arrays.<T> asList()); //Arrays.asList() would not compile
        }
        public static <T> List<T> m2(List<T> l) {
            return l;
        }
    }