通过varargs参数可能导致堆污染 [英] Possible heap pollution via varargs parameter

查看:88
本文介绍了通过varargs参数可能导致堆污染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解在使用具有通用类型的varargs的Java 7时会发生这种情况;

I understand this occurs with Java 7 when using varargs with a generic type;

但是我的问题是..

Eclipse说使用它可能会污染堆?"的确切含义是什么?

What exactly does Eclipse mean when it says "its use could potentially pollute the heap?"

还有

新的@SafeVarargs注释如何防止这种情况?

How does the new @SafeVarargs annotation prevent this?

推荐答案

堆污染是一个技术术语.它引用的引用类型不是其指向的对象的超类型.

Heap pollution is a technical term. It refers to references which have a type that is not a supertype of the object they point to.

List<A> listOfAs = new ArrayList<>();
List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As

这可能导致无法解释"的ClassCastException s.

This can lead to "unexplainable" ClassCastExceptions.

// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0); 

@SafeVarargs完全不会阻止此操作.但是,有些方法证明不会污染堆,编译器无法证明这一点.以前,此类API的调用者会收到烦人的警告,这些警告是完全没有意义的,但必须在每个调用站点中都加以抑制.现在,API作者可以在声明站点中将其取消一次.

@SafeVarargs does not prevent this at all. However, there are methods which provably will not pollute the heap, the compiler just can't prove it. Previously, callers of such APIs would get annoying warnings that were completely pointless but had to be suppressed at every call site. Now the API author can suppress it once at the declaration site.

但是,如果该方法实际上是安全的,则将不再警告用户.

However, if the method actually is not safe, users will no longer be warned.

这篇关于通过varargs参数可能导致堆污染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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