Is it dirt pollution?

I have a constructor like below

public MyConstructor(MyObject<T> ... objects) { // ... } 

Eclipse warns me with the following message:

Security type: potential heap pollution through varargs parameter objects

I modify the constructor as follows:

 public MyConstructor(MyObject<T>[] objects) { // ... } 

Now the warning disappears. However, I think the potential danger has not been resolved.

How is this workaround?

+7
java generics variadic-functions heap-pollution
source share
2 answers

In a way, this is a workaround. Creating arrays of an unsupported component type is unsafe. Therefore, such expressions for creating an array are prohibited by the compiler:

 // List<String> is erased to List => disallowed Object example = new List<String>[] { null, null }; // List<?> is effectively reifiable => allowed Object example = new List<?>[] { null, null }; 

However, hidden arrays are allowed using arity variable methods such as Arrays.asList .

 // RHS amounts to Arrays.asList(new List<String>[] { null, null }) List<List<String>> example = Arrays.asList(null, null); 

Since you have forbidden the creation of this array, your heap can no longer be polluted. But: What are you going to call this constructor?

Note that your constructor may not pollute the heap at all. The only way to do this is if

  • it converts the array to a less specific type (i.e. MyObject<?>[] or Object[] ) or
  • it allows the array to somehow escape (i.e. assign it to a field and return from the recipient or pass it to a potentially dangerous method).

If you do not, you can mark the constructor as having @SafeVarargs and the warning will disappear.

+6
source share

However, due to type erasure, the compiler converts the formal parameter Object[] varargs. Therefore, there is the possibility of contamination of the heap.

As we know, the reason for this warning is mainly based on erasing styles; now it is clearly stated in Java Docs for Heap Pollution , which

If you make sure your code compiles without warning, then heap contamination cannot occur.

And more about that

The compiler already generated a warning when it translated varargs formal parameter List<String>... l to the formal parameter List[] l . This statement is valid ; the variable l is of type List[] , which is a subtype of Object[] .

So,

Consequently, the compiler does not give a warning or error if you assign a List object of any type to any element of the array objectArray.

All quoted operators are copied from Java Doc

+2
source share

All Articles