So, I am delving into Java and curious about this type parameter usage.
<T>T getInstance
and then the arg
Class<T> type
I am a little confused here because if we require a return type, thus denoted by T then why isn't the arg the same... for instance
private static String getInstance(String arg)
So I'd figure it would be
private static Class<T> getInstance(final Class<T> type)
so, I am confused why the difference in expression of return type vs. argument
There is no need to have the return type the same as the parameter type and by no means any rule that dictates that.
When a method is defined as
private static <T> T getInstance(final Class<T> type)
it means that the return object will be of type T
, whereas the argument passed to the method is an instance of the generic java.lang.Class
type parameterized to T
.
This means the method may be invoked as follows:
String string = getInstance(String.class);
Hence this method takes an instance of type Class
and returns an object of the type corresponding to this Class
argument.
On the other hand, when the method is defined as
private static <T> T getInstance(final T type)
then you are forced to pass an object of type T
in order to get the instance. Imagine it will be called as follows:
String string = getInstance("a");
Notice how the object "a" of type String
is quite different than String.class
of type Class
.
T
and Class<T>
are totally different.
The first says, "an object of some type, T." The second says, "an object of type java.lang.Class
, which represents the class for some type T
."
Put another way, here are two possible implementations:
Class<T> getInstance(Class<T> type) {
return type;
}
T getInstance(Class<T> type) {
return type.newInstance();
}
For instance, if T
is a String
, then the first of those will return String.class
, and the second will return an empty string, ""
.
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