When generics fail, can I get an example? [closed]
I just have a general question about generics. I've used them for years and heard about how they are not perfect because they are stripped of their type at compile time (correct?). I am having a hard time finding examples or explanations of particular code that causes them to f开发者_运维百科ail. Can anybody give a code example and/or explain?
What you are referring to is Type Erasure, where the compiler removes all information related to type parameters and type arguments within a class or method. An example where this can be a detriment is:
ArrayList<String> stringList = new ArrayList<String>();
ArrayList<Integer> integerList = new ArrayList<Integer>();
System.out.println(stringList.getClass().
isAssignableFrom(integerList.getClass()));
We would hope this would print false, but it in fact prints true. There is no class distinction between stringList
and integerList
.
The thing is pretty straightforward. In Java, Generics are implemented as a compiler feature, not a bytecode feature.
So, when compiler finds something like this:
public List<String> getStrings() {
return new ArrayList<String>();
}
It translates to bytecode code that does not know anything about generics.
So, something you lack is the ability to infer generic information when you do reflection on the class that has that method.
On the other hand, in .NET framework the language (C#) and the runtime know about generic.
This code will for instance fail due to erasure:
if (someList instanceof List<String>)
someList.add(myString);
The instanceof
expression is evaluated at runtime, at which point the type parameter of someList
is no longer available.
What cases have you seen where generics would fail (at runtime i presume)? I'm not sure if a generic object would have the chance to fail - my first guess is that this would be caught by the compiler, thus telling you that there is a type mismatch or whatever since Generics ensure type-safety.
http://msdn.microsoft.com/en-us/library/ms172192.aspx
精彩评论