Reproduced from: Flower smile
Since Java 5 introduced generics, the pros and cons of Java and C + + for the different implementations of generics have been a conversation after dinner. In many of my previous training, when it comes to Java generics, it is always compared to the implementation of C + +, and it is generally concluded that
- Java uses type erasing, and generic information is only used for Javac for type checking at compile time and is Javac erased after compilation and cannot be reflected
- C + + uses code templates to implement generics, that is, when preprocessing generates generic classes like the List_int?,?list_char?, while solving the Java Runtime pseudo-generics problem, it causes the compiled code to grow linearly
- So in general, Java type Erasure achieves better
These three articles are already much more profound than most Java trainer speakers. But what if someone asks below? Under what circumstances is C + + 's implementation better than it can not be reflected, I can hardly catch a convincing example. Today, Spring's resttemplate finally gave me this example.
I have the following problems (reading requires some spring MVC, rest Basics)
There is an MVC method that returns a type of list:
1 |
|
2 |
@RequestMapping (value = "...", method = Requestmethod.get) |
3 |
@ResponseBody |
4 |
Public list<domainclass> dosomethingrest () { |
5 |
List<domainclass> Domainobjs = ...; |
6 |
return DOMAINOBJS; |
7 |
} |
8 |
|
At run time, Spring MVC converts the list to a JSON string and returns to the client. But if I use resttemplate to call the rest interface directly in another service, the problem is:
1 |
|
2 |
list<domainclass> Domainobjs = This.restTemplate.getForObject (This.resturl, List.class); |
3 |
|
The key is the second parameter, which is the type of the return value, and Resttemplate chooses the appropriate messageconverter based on this type to deserialize the return value of the calling rest interface into an object that matches the type. Because the generic parameter of list is erased at compile time, Resttemplate is unable to determine the contents of the list. In general? (the rest interface return value is not a list type) there is no problem, but coincidentally, if the server side uses JSON to serialize rest results , the return value is encapsulated in the list, and spring cannot tell if the developer wants to get the JSON content directly from the list package or to use the Jackson Library to deserialize the JSON into a Java object. In reality, Spring chooses the former and then throws ClassCastException
Searching the internet, someone has submitted a enhancement request to spring (here and here, where the first link in Walkaround can work), but there is no milestone
–eof–