I need to extend an abstract class which I can not modify:
public abstract class CustomField<T> extends AbstractField<T> implements HasComponents {
// some code
@Override
public abstract Class<? extends T> getType();
// some code
}
With a generic class like this:
public class VerticalCheckBoxSelect<T> extends CustomField<Set<T>> {
@Override
public Class<? extends Set<T>> getType() {
return ???;
}
}
My question is obvious: what should be returned by VerticalCheckBoxSelect::getType
to be compilable (and correct)?
You can return Class.class.cast(HashSet.class);
Which will compile, but will give you an unchecked assignment warning.
What you are actually doing is somehow equivalent to this,
public class VerticalCheckBoxSelect<T> extends CustomField<Set> {
@Override
public Class<? extends Set> getType() {
return ???;
}
}
Note that on the first line it says extends CustomField<Set>
which means that public abstract Class<? extends T> getType()
should be implemented in a way that it will always return Class<Set>
, so your implementation should be:
public class VerticalCheckBoxSelect<T> extends CustomField<Set<T>> {
@Override
public Class<? extends Set<T>> getType() {
@SuppressWarnings("unchecked")
Class<Set<T>> r = (Class) Set.class;
return r;
}
}
The above code is now perfectly compilable. Try it!
Now, let's say that you want it to be of arbitrary subclass of Set
like HashSet
, then replace the above Set.class
with HashSet.class
:
public class VerticalCheckBoxSelect<T> extends CustomField<Set<T>> {
@Override
public Class<? extends Set<T>> getType() {
@SuppressWarnings("unchecked")
Class<Set<T>> r = (Class) HashSet.class;
return r;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With