This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes generics question, type mismatch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "generics question, type mismatch" Watch "generics question, type mismatch" New topic

generics question, type mismatch

Denis Wen
Ranch Hand

Joined: Nov 11, 2008
Posts: 33

I am having this error "Type mismatch: cannot convert from Class<capture#3-of ? extends Object> to Class<V>". Everything looks fine to me, shouldn't value.getClass() return variable of type Class<V>?

public abstract class NotifyCache<K,V> implements Cache<K,V> {
protected void notifyPut(K key, V value) {
Class<V> clazz = value.getClass(); //error here
//doing stuff....

Henry Wong

Joined: Sep 28, 2004
Posts: 20373

Everything looks fine to me, shouldn't value.getClass() return variable of type Class<V>?

Yeah. You would think that it would be the case? But it's not.

The getClass() method is from the Object class. And the Object class is not a generic class. So, the getClass() method returns a Class object of an unknown type (? that extends Object, to be exact).

IMO, I think they purposely didn't make the Object support generics, and the reason is because it would be too annoying to fix everything -- since everything inherits from the Object class.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Rob Spoor

Joined: Oct 27, 2005
Posts: 20192

You know that value is an instance of V, but you can't know the exact class.

If V is a class, value can be of a sub class of V. For instance, if V is Number, then value.getClass() will return Integer.class (which is a Class<Integer> object) if value is actually an Integer object.

If V is an interface however, value can be of any class as long as it implements V. This is why value.getClass() does not even return a Class<? extends V>.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: generics question, type mismatch
It's not a secret anymore!