Why not use class for Java – t getInstance (final type)?

So I'm delving into Java and curious about the use of this type parameter

<T>T getInstance

Then arg

Class<T> type

I'm a little confused here, because if we need a return type represented by T, why arg is not the same... For example

private static String getInstance(String arg)

So I think it will be

private static Class<T> getInstance(final Class<T> type)

Therefore, I am puzzled why the return type is different from the expression of the parameter

Solution

There is no need to make the return type the same as the parameter type, and it is by no means any rule

When the method is defined as

private static <T> T getInstance(final Class<T> type)

It means that the type of the returned object is t, and the parameter passed to the method is a generic Java. Java. Net parameterized to t Instance of lang.class type

This means that the method can be called as follows:

String string = getInstance(String.class);

Therefore, this method takes an instance of type class and returns an object of type corresponding to this class parameter

On the other hand, when the method is defined as

private static <T> T getInstance(final T type)

Then you are forced to pass a T - type object to get the instance Imagine that it will be called as follows:

String string = getInstance("a");

Note that the object "a" of type string is different from the string of type class Class is very different

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>