• Post Reply Bookmark Topic Watch Topic
  • New Topic

Cast issue (when using generics)  RSS feed

 
Robert Merwe
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Given the code below, I get the following compiler error: Type mismatch: cannot convert from Object to String
What I don't understand, is why the compiler is unable to resolve T to String in this case (by simply removing <X> (which isn't used), or eg declaring newShape as Shape<Integer> all works fine)

 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Robert,

Welcome to JavaRanch!

That's an interesting observation, and I don't have a ready explanation for it. I suspect the answer is to be found in this section of the language spec, but only with a lot of heavy lifting:

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#341287

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Apparently when you drop generics in the declaration, it drops generics completely. Not just the class' generic types but also the method generic types. If you change the declaration in the easiest thing (Shape<?> newShape = ...) it works again.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!