Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method invocation with <T>

Tags:

java

generics

jls

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?

like image 660
Michał Kupisiński Avatar asked Feb 12 '13 18:02

Michał Kupisiński


People also ask

What does T stand for in generics?

< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.

What does the T designator indicate in a generic class?

Its instances (only one per type exists) are used to represent classes and interfaces, therefore the T in Class<T> refers to the type of the class or interface that the current instance of Class represents.

How do you use T generics in Java?

It specifies the type parameters (also called type variables) T1, T2, ..., and Tn. To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.

What is the difference between T and E in Java generics?

6 Answers. Show activity on this post. Well there's no difference between the first two - they're just using different names for the type parameter ( E or T ).


1 Answers

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;
    }
}
like image 87
assylias Avatar answered Oct 12 '22 21:10

assylias