Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic method type casting

Tags:

java

generics

Why this happened? One line in the code works well while the other similar line doesn't. Does the automatic type cast only happen in certain conditions? I have tried to assign gt.echoV() to an Object and it works well; but when I assign it to a String, the same error will come out again.

public class GeneMethodTest {

    public static void main(String... args) {
        GeneMethodTest gt = new GeneMethodTest();
        gt.<String>echoV(); //this line works well
        gt.<String>echoV().getClass();//this line leads to a type cast exception                                                          
    }

    public <T> T echoV() {
        T t=(T)(new Object());                                                                    
        return t;
    }
}
like image 732
charles_ma Avatar asked Jul 31 '13 18:07

charles_ma


1 Answers

gt.<String>echoV().getClass(); produces the equivalent of the following sequence of operations:

// Inside echoV
Object t = new Object();  // Note that this is NOT a String!
Object returnValue = t;
// In main
String stackTemp = (String) returnValue;  // This is the operation that fails
stackTemp.getClass();

What you get "for free" with generics is that (String) cast. Nothing else.

like image 188
Hot Licks Avatar answered Sep 22 '22 19:09

Hot Licks