Transferred from:
Http://blog.sina.com.cn/s/blog_617a491c0100eox7.html
Java generic methods are widely used when method return values are container class objects.
Public static list <t> Find (class <t> clazz, string userid ){
....
}
Generally, when writing a Java generic method, the return value type and at least one parameter type should be generic, and the type should be consistent. If only the return value type or one of the parameter types uses the generic type, the usage of this generic method is greatly limited, basically to the same level as that of the non-generic method.
The following describes how to use two very similar Java generic methods and their differences.
First:
Public static <t extends commonservice> T getservice (class <t> clazz) {
T service = (t) servicemap. Get (clazz. getname ());
If (service = NULL ){
Service = (t) servicelocator. getservice (clazz. getname ());
Servicemap. Put (clazz. getname (), service );
}
Return service;
}
Second:
Public static <t> T getservice (class <? Extends commonservice> clazz) {
T service = (t) servicemap. Get (clazz. getname ());
If (service = NULL ){
Service = (t) servicelocator. getservice (clazz. getname ());
Servicemap. Put (clazz. getname (), service );
}
Return service;
}
The following is the class of the generic method:
Public abstract class commonservice {
Private Static hashmap <string, commonservice> servicemap = new hashmap <string, commonservice> ();
// Generic method definition
.
.
.
}
The two generic methods only have different signatures and the same method bodies. What are the differences between them?
Let's use them to understand their differences.
Use the following generic method:
Public class main {
Public static void main (string [] ARGs ){
Noticeservice = commonservice. getservice (noticeservice. Class); // use the first generic method correctly without compilation errors.
Noticeservice = commonservice. getservice (userservice. Class); // The first generic method is incorrectly used, Compilation errors may occur. .
}
}
Use the following generic method:
Public class main {
Public static void main (string [] ARGs ){
Noticeservice = commonservice. getservice (noticeservice. Class); // use the second generic method correctly without compilation errors, correct logic, and running exceptions.
Noticeservice = commonservice. getservice (userservice. Class );//Incorrect use of the second generic method will not cause compilation errors, but the logic is incorrect and an exception will occur during running. , Dangerous!
}
}
Now I know the differences between these two extremely similar generic methods?
The first generic method: the return value is of the same type as the parameter value, which is recommended;
The second generic method: the type of the returned value and the parameter value is not the same. Please be careful or avoid using it.