I am new to Generics and am having an issue.
Consider the following code:
public class A {}
public class B extends A {}
public <T extends A> T getB()
{
A test = new B();
Class<B> clazz = B.class;
if (clazz.isInstance(test))
{
return (T)test;
}
return null;
}
This generates an Unchecked cast warning. on the return (T)test;
line.
but clearly I am checking the type with the if (clazz.isInstance(test))
line.
Is there a way to do a "checked cast"?
I'm not looking to just suppress the warning but actually implement a checked cast. Unfortunately I can't find information on how to perform a checked cast.
Is there a way to do a "checked cast"?
Sure, although it's important to note that it doesn't really help you here, because your method is hard-coded to use B
in a few places. You can perform the cast with:
clazz.cast(test)
... but that will cast to B
, not T
. In particular, suppose I ran:
public class C extends A {}
...
C c = foo.<C>getB();
How would you expect that to work?
You might want to change your code to something like:
public <T extends A> T getB(Class<T> clazz)
{
A test = // get A from somewhere
return clazz.isInstance(test) ? clazz.cast(test) : null;
}
Then that's fine, because clazz.cast
will return a value of type T
, which you're fine to return.
See more on this question at Stackoverflow