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?
< 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.
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.
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.
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 ).
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With