So java has type erasure, which deletes the type arguments (no generic types at runtime). Can someone explain why the supertype type arguments are preserved then?
class StringList extends ArrayList<String> {
public Type getType() {
Type[] typeArguments = ((ParameterizedType) this.getClass()
.getGenericSuperclass()).getActualTypeArguments();
return typeArguments[0];
}
}
What this means basically is:
new ArrayList<String>()// I cannot use reflection to find out the generified type String
but
new StringList()//I can use reflection to see the generic type String
So type erasure is for backwards compatibility, but why are the supertype type arguments preserved then? Is the metadata updated to support it?
Why the one and not the other?
Like generics in C# and Java, parameterized types allow you to create “containers” that can hold other types. For example, List<String> represents a List containing only strings, and KeyValuePair<int, string> represents a pair of values in which an int serves as a key to a string .
Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
It's done for compile time type safety. If the super class of StringList
was erased to ArrayList
, there would be no way to protect against
StringList stringList = new StringList();
stringList.add(new Integer(123456));
If the type remains in the .class
file for StringList
, the compiler can correctly refuse the source code above since new Integer(123456)
is not of type String
expected by ArrayList<String>#add(String)
.
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