Showing posts with label SafeVarargs. Show all posts
Showing posts with label SafeVarargs. Show all posts

Friday, 22 July 2022

Falling into a trap: decompiling java code

So my colleague was decompiling some Java code. We're using IntelliJ and then it happens automatically if you happen to select a Class file or something referencing a class file for which there are no sources attached.

And for the life of us, we couldn't understand why that code seemed to work.

Here's the decompiled code snippet.

protected Block createItem(String title, ItemProperties properties) {
  return this.createItem(title, properties);
}

It looked like it was going in circles, as the method was simply calling itself. This is bound to create a StackOverflowError when enough recursion happens.

However, no such problem occurred.

When looking at the source, however, we found it was not similar to the decompiled code:

protected Block createItem(String title, ItemProperties properties) {
  return createItem(title, properties, new SubItem[0]);
}

What turned out to be the issue, an empty array as the varargs at the end of a method is simply removed in the decompiled class version.

Hence our confusion.

It took us several minutes to find this out.

References

Baeldung - Varargs
https://www.baeldung.com/java-varargs

Thursday, 20 October 2016

Potential heap pollution via varargs parameter

Reifiable versus Non-Reifiable

Type erasure is an important "feature" of Generics in Java. It means generics are not available at runtime, as they are effectively removed during compiling.

The reference in [1] has a much better explanation.

To quote:
“A reifiable type is a type whose type information is fully available at runtime.”
“Non-reifiable types are types where information has been removed at compile-time by type erasure.”

Generics versus Arrays

In Java, generics are non-reifiable and arrays are reifiable.

Problems can occur when we combine these two together.

Combining these two together can happen when using the varargs construction in Java.

The reason for this is that the varargs way of using method parameters is translated within the method as a array.

This can cause Heap pollution2 when combined with Generics.

As the compiler doesn't know when this happens (it depends on how the method deals with it), it throws out the warning.

Hence the need for the @SafeVarargs3 annotation for those methods where the software designers are certain the problem does not occur.

References

[1] Non-Reifiable Types
http://docs.oracle.com/javase/tutorial/java/generics/nonReifiableVarargsType.html
[2] 9.6.3.7. @SafeVarargs
http://docs.oracle.com/javase/specs/jls/se7/html/jls-9.html#jls-9.6.3.7
[3] Oracle JavaDoc - SafeVarargs
http://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html
StackOverflow - Potential heap pollution via varargs parameter
http://stackoverflow.com/questions/12462079/potential-heap-pollution-via-varargs-parameter