I want to cast Object
to List<IAnalysisData>
. The object was read in from a database. However, I am getting an annoying warning saying that the cast is unchecked.
private List<IAnalysisData> deserialize(byte[] bytes) throws IOException, ClassNotFoundException
{
List<IAnalysisData> analysisDataList = null;
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream oos = new ObjectInputStream(in);
Object o = oos.readObject();
analysisDataList = (List<IAnalysisData>) o; //warning here
return analysisDataList;
}
What is the proper way to cast an object?
EDIT: I forgot to mention that IAnalysisData
is an interface. The implementation is called AnalysisData
.
The only way I know to fix something like this would be to add the
@SuppressWarnings("unchecked")
There's no way to prove what you're doing is safe really, even if you absolutely 'know' that it is.
So it would look like
@SuppressWarnings("unchecked")
private List<IAnalysisData> deserialize(byte[] bytes) throws IOException, ClassNotFoundException
{
List<IAnalysisData> analysisDataList = null;
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream oos = new ObjectInputStream(in);
Object o = oos.readObject();
analysisDataList = (List<IAnalysisData>) o; //warning here
return analysisDataList;
}
You'll get no unchecked warning in that method after that.
It is not possible to check a cast to a generic type. You could use instanceof
to confirm that Object o
really is a List<?>
but you cannot confirm that it is a List<IAnalysisData>
. For safety, you could use a try/catch block to catch a ClassCastException
, but that will still not hide the IDE warning. Like Andrew said, putting the @SuppressWarnings("unchecked")
above the method will hide the warning for this method alone, but IDE warnings mean next to nothing in the long run.
Your casting syntax is fine.
You ought to check that analysisDataList
is not null
, which indicates casting success. That's what your IDE is telling you.
Encode this in a separate function if you use it in more than one place.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.