Thursday, September 09, 2010

Type erasure does not erase all of it


Last week I was reading the most recent installment of Spring framework reference documentation and one particular thing surprised me, if not to say more. Here it is with my annotations:


In Java 5 and later, you can use strongly typed collections { sure } [...] If you are using Spring to dependency-inject a strongly-typed Collection into a bean, you can take advantage of Spring's type-conversion support such that the elements of your strongly-typed Collection instances are converted to the appropriate type { something rings a bell but I am not sure... } prior to being added to the Collection.


public class Foo {

private Map<String, Float> accounts;

public void setAccounts(Map<String, Float> accounts) {
this.accounts = accounts;
}
}
<beans>
<bean id="foo" class="x.y.Foo">
<property name="accounts">
<map>
<entry key="one" value="9.99"/>
<entry key="two" value="2.75"/>
<entry key="six" value="3.99"/>
</map>
</property>
</bean>
</beans>


When the accounts property of the foo bean is prepared for injection, the generics information about the element type of the strongly-typed Map is available by reflection { really? I thought no generic info is available at run time. That's what type erasure is about, isn't it? }. Thus Spring's type conversion infrastructure recognizes the various value elements as being of type Float, and the string values [...] are converted into an actual Float type { something is not right. Guys from springsource are not likely to make false statements of this magnitude, or are they? }


I never really looked into all new stuff that Generics brought along with them into the language. And I missed a small but apparently important portion of what has been added to the Java reflection classes.

Here's a short summary at stackoverflow that basically sums up what you can get via reflection. It's not like you can get anything, the exact type of the object at hand has still been erased and instance of ArrayList is still just an instance of an ArrayList. But something is still there :)

Two more good readings on the subject:


No comments: