Generic Java method casting

Why did this happen? One line in the code works well, and another similar line does not. Is automatic type performed only under certain conditions? I tried to assign gt.echoV () to an object, and it works well; but when I assign it to String, the same error will fail 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; } } 
+6
source share
3 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 a (String) cast. Nothing more.

+4
source

It works fine, nothing special, normal use of generics

 gt.<String>echoV(); //this line works well 

Here we have something less obvious. Since a generic method is defined at runtime, jvm does not know which Generic class will return in compiletime, therefore classTypeException

 gt.<String>echoV().getClass();//this line leads to a type cast exception 

you should first assign it to a variable since jvm knows the type of the variable in compiletime

 String s = gt.<String>echoV(); s.getClass(); 
+2
source

change this line:

 gt.<String>echoV().getClass(); 

in

 (gt.echoV()).getClass(); 

and he will compile
(it will return: class java.lang.Object )

The root of a ClassCastException is that the method returns t (the generic type t , which is an object), and you are trying to dump it to String. You can also change your return code:

 return (T)"some-string"; 

to remove the error.

Generic is used by the compiler to check what type of object to expect so that it can catch errors that the developer made during compilation (as compared to errors at runtime). Therefore, IMHO uses this method of using generics.

+1
source

Source: https://habr.com/ru/post/950748/