• Post Reply Bookmark Topic Watch Topic
  • New Topic

Different behavior in generic interface declarations  RSS feed

 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry about the topic of this post, I couldn't think of a more descriptive name. I can't seem to figure out why this piece of code works (albeit with a warning):


when this one generates a compiler error:


It seems to me that they are both passing an Object as an argument to a method that takes a more specific type, and yet one works and the other doesn't. I know it has to do with the interface being specified as the raw type in the first example, and I suspect type-erasure plays a part (as it does with all strange behavior regarding generics). But I can't convince myself of any good argument.
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may be over thinking it.

A plain Resolver has a resolve(Object) method.

A Resolver<String> has a resolve(String) method.

You can assign (with a warning) a Resolver<String> to a Resolver variable, and once you've done so, it's just as if you've assigned a String to an Object variable: the compiler treats the thing as if the variable's type is all that matters.

So in the first case, you're calling resolve(Object) on an Object, and it works.

In the second case, you're calling resolve(String) on an Object, and it doesn't.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
You may be over thinking it.

A plain Resolver has a resolve(Object) method.

A Resolver<String> has a resolve(String) method.

You can assign (with a warning) a Resolver<String> to a Resolver variable, and once you've done so, it's just as if you've assigned a String to an Object variable: the compiler treats the thing as if the variable's type is all that matters.

So in the first case, you're calling resolve(Object) on an Object, and it works.

In the second case, you're calling resolve(String) on an Object, and it doesn't.


I can accept that explanation, so if I write it this way, is there an implicit cast from the Object that was passed as a parameter to an Integer?
 
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes - and you are right, it has to do with erasure.

In the byte code, r will invariably have a resolve(Object) method, which inside it contains the cast to Integer.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!