So here’s my code :
public class SetWritable<T extends Writable> implements Writable {
private Class<? extends Writable> valueClass;
private Set<T> values;
public SetWritable(Class<T> valueClass) {
this.valueClass = valueClass;
this.values = new HashSet<T>();
}
public void readFields(DataInput in) throws IOException {
values = new HashSet<T>();
int len = in.readInt();
for (int i = 0; i < len; i++) {
//this line is where I get the warning
//FYI, WritableFactories.newInstance returns an instance of Writable
T value = (T) WritableFactories.newInstance(valueClass);
value.readFields(in);
values.add(value);
}
}
}
What’s confusing to me is this : I’ve asserted that T extends Writable, so why am I getting a warning when I try to cast the Writable to T? And since I know T extends Writable, is it safe to suppress this warning?
You are getting the warning because
WritableFactories.newInstancereturns aWritableand yourTextendsWritable, so it might not be a safe cast. However, since you are usingClass<T>as your argument tonewInstanceit is safe to suppress this warning.It might be better to store
valueClassasClass<T>and useClass#castto cast for you, then you won’t have any ugly@SuppressWarningshanging over your method.