Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<T>T getInstance(final Class<T> type) why not Class<T> for both?

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

like image 595
james emanon Avatar asked Dec 01 '22 18:12

james emanon


2 Answers

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.

like image 74
M A Avatar answered Dec 05 '22 10:12

M A


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, "".

like image 22
yshavit Avatar answered Dec 05 '22 10:12

yshavit