为什么上传一个班级被认为是不安全的操作? [英] Why is upcasting a Class considered an unsafe operation?

查看:98
本文介绍了为什么上传一个班级被认为是不安全的操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在编译 Class <?c>时Java编译器会触发unchecked cast警告?将Object> 扩展为 Class< Object> ?这种转换可能会失败吗?

Why does the Java compiler trigger an "unchecked cast" warning when casting Class<? extends Object> to Class<Object>? How could this cast possibly fail?

推荐答案

这样的转换根本不安全 ,并且无法检测到 Class 类安全的事实。试想像这样的一个类:

Such a cast is simply not safe in general, and the fact that it is safe for the Class class can not be detected. Imagine a class like this:

// Hypothetical!
class MyClass<T> extends Class<T> {
    public T someInstance;
}

现在,如果有问题的演员被允许,你可以做一些类似于

Now, if the cast in question was allowed, you could do something like

MyClass<Integer> myClassWithInteger = new MyClass<Integer>();
myClassWithInteger.someInstance = someInteger;

// This is valid
MyClass<? extends Object> myClassWithWildcard = myClassWithInteger; 

// This is NOT valid, but let's assume it was:
MyClass<Object> myClassWithObject = myClassWithWildcard; 

// This would be valid, because 'someInstance' was of type 'Object' here
myClassWithObject.someInstance = "someString";

// This is valid. But through the unchecked cast, we silently
// sneaked in an STRING as this instance. So this would fail:
Integer i = myClassWithInteger.someInstance;

您在评论中提出:

You asked in the comment:


你是说语言作者想要避免像Class这样的安全课程的特殊处理,所以他们全面禁止这样做?

Are you saying that the language authors wanted to avoid special treatment for safe classes like Class so they forbid this across the board?

是的。关键的一点是,这样的演员阵容是否安全的问题取决于该类的语义不能检测到安全性

Yes. The crucial point is that the question whether such a cast is safe or not depends on the semantics of the class. The safety can not be detected syntactically.

这篇关于为什么上传一个班级被认为是不安全的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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