I am reading Thinking in java , Generics. In one example(at paragraph “The action at the boundaries”)
public class GenericHolder<T> {
private T obj;
public void set(T obj) { this.obj = obj; }
public T get() { return obj; }
public static void main(String[] args) {
GenericHolder<String> holder =
new GenericHolder<String>();
holder.set("Item");
String s = holder.get();
}
} ///:~
public void set(java.lang.Object);
0: aload_0
1: aload_1
2: putfield #2; //Field obj:Object;
5: return
public java.lang.Object get();
0: aload_0
1: getfield #2; //Field obj:Object;
4: areturn
public static void main(java.lang.String[]);
470 Thinking in Java Bruce Eckel
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 set:(Object;)V
14: aload_1
15: invokevirtual #7; //Method get:()Object;
18: checkcast #8; //class java/lang/String
21: astore_2
22: return
According to the disassembled code line 18, the compiler adds the checkcast code. I want to know if it is always to such a checkcast for generic. I replaced the String to Integer and tried again, but I didn’t find the checkcast code at last. So does the Object type.
Could someone explain that? Is String in Java is a special Object?
For me it produces a
checkcastalso forInteger:As you can see, the
getmethod has the signatureLjava/lang/Object;i.e., thecheckcastis to make sure that theObjectreturned is indeed anInteger.Edit: In the code you posted as a comment:
you pass on the returned value to
PrintStream.printwhich accepts anObject. Thus, there is no need to cast the returned value. (checkcast java.lang.Objectwould always go through!)