Java generic methods:
I won't say much about what generics mean, and the definition of generic classes in Java is also relatively simple, for example: 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>();, indicating that the type of generic T is Object.
But generic methods in Java are more complicated.
A generic class indicates the specific type of a generic when instantiating a class; a generic method indicates the specific type of a generic when calling a method.
The syntax format for defining a generic method is as follows:
The syntax format of calling a generic method is as follows:
To explain, when defining a generic method, you must add a <T> to the return value to declare that this is a generic method, holding a generic T, and then you can use generic T as the return value of the method.
The function of Class<T> is to indicate the specific type of a generic type, and the variable c of the Class<T> type can be used to create objects of a generic class.
Why use variable c to create an object? Since it is a generic method, it means that we don’t know what the specific type is or what the constructor method is. Therefore, there is no way to new an object, but we can use the newInstance method of the variable c to create an object, that is, use reflection to create an object.
The parameters required by a generic method are of type Class<T>, and the return value of the Class.forName() method is also Class<T>, so Class.forName() can be used as a parameter. Among them, what type is the parameter in the forName() method, and what type is the returned Class<T>. In this example, the forName() method is passed in the complete 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 just have one parameter Class<T>, but other parameters can be added as needed.
Why use generic methods? Because generic classes need to indicate the type when instantiated, if you want to change a type, you have to renew it, which may not be flexible enough; while generic methods can indicate the type when called, which is more flexible.
Thank you for reading, I hope it can help you. Thank you for your support for this site!