Is this a safe way to create an instance (assuming T has a accessible default constructor) ?
<T>
public T defaultObj(T obj) throws Exception {
return (T) obj.getClass().newInstance();
}
Because of the type erasure, the above codes will generate an unchecked warning. Is it possible to get rid of this warning other than @SuppressWarnings?
Many thanks in advance!
Edit:
Yes, I know if I could pass a class<T> type which would be much better. But let’s just assume it is out of question for now.
That’s exactly what
@SuppressWarningsis supposed to do: this code is safe (because callinggetClass()on an object of typeTactually yieldsClass<? extends T>), but compiler cannot understand it (return value ofgetClass()is declared asClass<?>due to limitations of generics) and generates warning.It’s absolutely legal to use
@SuppressWarningsin this case, and you shouldn’t try to avoid using it.