[英]Casting Object to List results in unchecked cast warning
I want to cast Object
to List<IAnalysisData>
. 我想将Object
List<IAnalysisData>
为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. 编辑:我忘了提到IAnalysisData
是一个接口。 The implementation is called AnalysisData
. 该实现称为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>
. 您可以使用instanceof
确认Object o
确实是List<?>
但不能确认它是List<IAnalysisData>
。 For safety, you could use a try/catch block to catch a ClassCastException
, but that will still not hide the IDE warning. 为了安全起见,您可以使用try / catch块来捕获ClassCastException
,但这仍然不会隐藏IDE警告。 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. 就像安德鲁所说的那样,将@SuppressWarnings("unchecked")
放在该方法之上将单独隐藏该方法的警告,但是从长远来看,IDE警告@SuppressWarnings("unchecked")
没有任何意义。
Your casting syntax is fine. 您的转换语法很好。
You ought to check that analysisDataList
is not null
, which indicates casting success. 您应该检查analysisDataList
不为null
,这表示转换成功。 That's what your IDE is telling you. 这就是您的IDE告诉您的。
Encode this in a separate function if you use it in more than one place. 如果在多个地方使用它,请将其编码为单独的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.