this post was submitted on 14 Jun 2023
15 points (100.0% liked)
Java
1388 readers
1 users here now
For discussing Java, the JVM, languages that run on the JVM, and other related technologies.
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Yeah, this is an example I talked about in another comment here but I can be more concrete. This and code like it is why I usually wondered why erasure happens at all. In the Jackson framework to convert JSON to a class you pass in the type like
MyClass.class
but because you can't pass in parameters you'd have to doList.class
. Jackson has this method to handle such situations. It uses theTypeReference
class which takes advantage of Java storing type parameters for anonymous classes. The Javadoc for that class mentions this blog which is sort of the de facto source for getting around this limitation. Essentially the code you write is like this,You make a new, anonymous implementation of
TypeReference<T>
andT
is known at runtime.I haven't looked into why Jackson has to do it that way but my best guess is the proper way would be inconvenient.
Ah, that makes sense!
I guess I haven't really run into many examples like this. The times I've run into code where the former developers clearly struggled with handling types correctly has nearly always been their own fault (bad interface, bad organization of data, etc)
Yeah, agreed. My first project as a junior dev was on Java 6 using something written before Java 5 that they sort of slapped generics all over for no apparent reason. So many warnings lol.