1. Description
During the compilation process, the information of type variables can be obtained. Therefore, the set method can be type checked in the compiler, and illegal types cannot be compiled. But for the get method, due to the erasure mechanism, the actual reference type during operation is the Object type.
In order to restore the type of the returned result, the compiler adds type conversion after get. Therefore, there is type conversion logic on line 18 of the main method body of the genericHolder.class file. This is added automatically by the compiler.
So we dealt with the read and write locations of generic objects and added restrictions to the code.
2. Example
//GenericHolder.java public class GenericHolder<T> { T obj; public T getObj() { return obj; } public void setObj(T obj) { this.obj = obj; } public static void main(String[] args) { GenericHolder<String> holder = new GenericHolder<>(); holder.setObj("Item"); String s = holder.getObj(); } } //GenericHolder.class public class GenericHolder<T> { T obj; public GenericHolder(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public T getObj(); Code: 0: aload_0 1: getfield #2 // Field obj:Ljava/lang/Object; 4: areturn public void setObj(T); Code: 0: aload_0 1: aload_1 2: putfield #2 // Field obj:Ljava/lang/Object; 5: return public static void main(java.lang.String[]); Code: 0: new #3 // class GenericHolder 3: dup 4: invokespecial #4 // Method "<init>":()V 7: astore_1 8: aload_1 9: ldc #5 // String Item 11: invokevirtual #6 // Method setObj:(Ljava/lang/Object;)V 14: aload_1 15: invokevirtual #7 // Method getObj:()Ljava/lang/Object; 18: checkcast #8 // class java/lang/String 21: astore_2 22: return }
The above is the detailed content of What is the principle of Java generic erasure. For more information, please follow other related articles on the PHP Chinese website!