It is well known, that generic types don't survive the compiling process. They are replaced by class casts.
But nevertheless, the type information is present in the class file and can be seen using reflection:
public class Demo
{
private List<String> list;
public Demo() throws SecurityException, NoSuchFieldException
{
System.out.println(((Class<?>)((ParameterizedType) getClass().getDeclaredField("list").getGenericType()).getActualTypeArguments()[0]).getName());
}
public static void main(String[] args) throws SecurityException, NoSuchFieldException
{
new Demo();
}
}
When executed, this will print java.lang.String
.
Can a JIT use this for some kind of optimization? Or is that information from the point of view of the JIT useless?
It could, but as far as I know it doesn't. To work around this, Scala added support somewhat recently to compile-time type specialization of generic code which generates specialized versions of the class - without any casts - and places them to the rest of the codebase transparently so that the code still works as expected. In these cases, compiled Scala code can actually be noticeably faster than Java since Java with Generics will always use casts.
Its not possible for the JVM to avoid casting the object as the underlying collection may not have Strings. e.g. if erasure is used to add an Integer to the list.
I can't think of a potential optimisation and there are plenty of potential optimisation the JIT doesn't do. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With