File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "generics question, type mismatch" Watch "generics question, type mismatch" New topic
Author

generics question, type mismatch

Denis Wen
Ranch Hand

Joined: Nov 11, 2008
Posts: 33
His,

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....
}
}

thanks
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19062
    
  40

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.

Henry


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

Joined: Oct 27, 2005
Posts: 19783
    
  20

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>.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: generics question, type mismatch