Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic Doubt

 
Anudeep Duvvuri
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



the output is
21
class java.lang.Integer

As per my knowledge in java we cannot cast Integer to String or vice versa in java but why is the String Type T is converted to Integer Type here

Please reply.

[Added code tags - see UseCodeTags for details]
 
Anudeep Duvvuri
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
anyone please clarify me
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please be patient.
 
Stephan van Hulst
Bartender
Pie
Posts: 5897
63
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Casting is a runtime operation, and at runtime generic type arguments are erased. So type parameters without an upper bound just act as regular Object types. Here's what your class looks like at runtime:
 
Anudeep Duvvuri
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok got it thank you
that means we can also cast a boolean type right???
 
Stephan van Hulst
Bartender
Pie
Posts: 5897
63
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can cast to any generic type parameter, as long as the upper bound is a supertype of the reference you're casting. It doesn't really make much sense though, because you'd always be casting upwards, which is useless.

For instance, if the class signature was public class ImplicitConv<T extends String> then the program would throw a ClassCastException, as expected.
 
Anudeep Duvvuri
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok thank you very much for replying
 
Ivan Jozsef Balazs
Rancher
Posts: 979
5
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> Here's what your class looks like at runtime:


$javap -private ImplicitConv

Compiled from "ImplicitConv.java"
public class ImplicitConv extends java.lang.Object{
java.lang.Object t;
public ImplicitConv(java.lang.Object);
void method();
public static void main(java.lang.String[]);
}
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
However, there is a compiler warning ("unchecked cast") on line 7. The compiler has been able to tell something was amiss and told you so. If you ignore or don't resolve generics-related compiler warnings, you risk getting ClassCastException at runtime.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic