What is the concept of erasure in generics in Java

2018-12-31 05:41发布

What is the concept of erasure in generics in Java?

标签: java generics
8条回答
荒废的爱情
2楼-- · 2018-12-31 06:27

Erasure, literally means that the type information which is present in the source code is erased from the compiled bytecode. Let us understand this with some code.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class GenericsErasure {
    public static void main(String args[]) {
        List<String> list = new ArrayList<String>();
        list.add("Hello");
        Iterator<String> iter = list.iterator();
        while(iter.hasNext()) {
            String s = iter.next();
            System.out.println(s);
        }
    }
}

If you compile this code and then decompile it with a Java decompiler, you will get something like this. Notice that the decompiled code contains no trace of the type information present in the original source code.

import java.io.PrintStream;
import java.util.*;

public class GenericsErasure
{

    public GenericsErasure()
    {
    }

    public static void main(String args[])
    {
        List list = new ArrayList();
        list.add("Hello");
        String s;
        for(Iterator iter = list.iterator(); iter.hasNext(); System.out.println(s))
            s = (String)iter.next();

    }
} 
查看更多
宁负流年不负卿
3楼-- · 2018-12-31 06:28

To summarize the previous answers:

In general, here is how erasure works. When your Java code is compiled, all generic type information is removed (erased). This means replacing type parameters with their bound type, which is **Object** if no explicit bound is specified, and then applying the appropriate casts(as determined by the type arguments) to maintain type compatibility with the types specified by the type arguments. The compiler also enforces this type compatibility.

This approach to generics means that no type parameters exist at run time. They are simply a source-code mechanism.

查看更多
登录 后发表回答