Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection, why are the supertype type arguments preserved at runtime

Tags:

java

generics

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 image 384
mist Avatar asked Jan 20 '15 16:01

mist


People also ask

Why are parameterized types important in Java?

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 .

Why use generic types Java?

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.

What is the purpose of using generics?

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.

What is Java reflection?

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.


1 Answers

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).

like image 134
Sotirios Delimanolis Avatar answered Oct 16 '22 08:10

Sotirios Delimanolis