类型安全:来自 Object 的未经检查的强制转换 [英] Type safety: Unchecked cast from Object

查看:22
本文介绍了类型安全:来自 Object 的未经检查的强制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将对象强制转换为我的 Action 类,但结果是警告:

I try to cast an object to my Action class, but it results in a warning:

Type safety: Unchecked cast from Object to Action<ClientInterface>

Action<ClientInterface> action = null;
try {
 Object o = c.newInstance();
 if (o instanceof Action<?>) {
  action = (Action<ClientInterface>) o;
 } else {
  // TODO 2 Auto-generated catch block
  throw new InstantiationException();
 }
 [...]

感谢您的帮助

推荐答案

是的 - 这是 键入擦除.如果 o 实际上是 Action 的一个实例,它不会被演员表捕获 - 您只会在尝试使用它时看到问题,传递在 ClientInterface 而不是字符串中.

Yes - this is a natural consequence of type erasure. If o is actually an instance of Action<String> that won't be caught by the cast - you'll only see the problem when you try to use it, passing in a ClientInterface instead of a string.

您可以使用以下方法消除警告:

You can get rid of the warning using:

@SuppressWarnings("unchecked")

作为一个函数注解,但你不能轻易理清根本问题:(

as a function annotation, but you can't easily sort out the underlying problem :(

这篇关于类型安全:来自 Object 的未经检查的强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆