Detailed explanation and simple examples of generic methods in Java

Java generic methods:

I won't say much about what generic means, and the definition of generic classes in Java is relatively simple, such as public class test < T > {}. This defines a generic class test. When instantiating this class, you must specify the specific type of generic T, for example: Test < Object > t = new test < Object > ();, Indicates that the type of generic t is object.

However, generic methods in Java are more complex.

Generic class indicates the specific type of the generic when instantiating the class; Generic method refers to the specific type of generic when calling the method.

The syntax format for defining generic methods is as follows:

The syntax format of calling generic methods is as follows:

To illustrate, when defining a generic method, you must add a < T > before the return value to declare that it is a generic method, hold a generic T, and then use the generic t as the return value of the method.

The function of class < T > is to indicate the specific type of generic class, and the variable C of class < T > type can be used to create the object of generic class.

Why create objects with variable C? Since it is a generic method, it means that we don't know what the specific type is or how to construct it. Therefore, there is no way to new an object, but we can use the newinstance method of variable C to create an object, that is, we can use reflection to create an object.

The parameter required by the generic method is class < T > type, and class The return value of the forname() method is also class < T >, so you can use class Forname() as a parameter. Among them, the type of the parameter in the forname () method is the type of the returned class < T >. In this example, the forname() method passes in the full path of the user class, so the object of type class < user > is returned. Therefore, when calling the generic method, the type of variable C is class < user >, so the generic t in the generic method is indicated as user, so the type of variable obj is user.

Of course, generic methods can not only have one parameter class < T >, but other parameters can be added as needed.

Why use generic methods? Because generic classes need to specify the type when instantiating. If you want to change a type, you have to new it again, which may not be flexible enough; Generic methods can specify the type when calling, which is more flexible.

Thank you for reading, hope to help you, thank you for your support to this site!

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
分享
二维码
< <上一篇
下一篇>>