shsteimer
shsteimer

Reputation: 28800

why do I need a cast in this situation?

if i have a method defined.

public static <T> T getSomeTea(Class<T> returnType) {
   //do stuff and return a T
}

public static <T> T getSomeSpecialTea(T someVal) {
   T someTea = (T) getSomeTea(someVal.getClass());
}

in getSomeSpecialTea, why do I need to cast the return from getSomeTea. it would seem to me the cast is unneccesary, but perhaps i'm missing something important.

Upvotes: 4

Views: 95

Answers (2)

irreputable
irreputable

Reputation: 45433

An unfortunate erasure on the return type of getClass() that bugs many people.

You can have a utility method that returns the unerased type

public static <T> Class<? extends T> myGetClass(T instance)
    return (Class<? extends T>)instance.getClass();

public static <T> T getSomeSpecialTea(T someVal) 
   T someTea = getSomeTea( myGetClass(someVal) );

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500185

Object.getClass() isn't generic, so your code is effectively:

public static <T> T getSomeSpecialTea(T someVal) {
   Class<?> clazz = someVal.getClass();
   T someTea = (T) getSomeTea(clazz);
}

At that point is it clearer why you need the cast? (Not that the cast will really anything at execution time, of course...) You're not calling <T>getSomeTea() which is what you really want to be doing, effectively.

It's just another case of Java generics being a bit of a pain :(

Upvotes: 4

Related Questions