In Java 17 I have a serializer that generates a tree structure. Before generating child entities, I increase the indention level; afterwards I decrease the indention level. Normally that should be done in a try/finally to keep the serializer from being left in a corrupt state if there is an error:
increaseIndentLevel();
try {
serializeChildren()
} finally {
decreaseIndentLevel()
}
Using try-with-resources I have created a clever and elegant little subframework that makes sure this is done, in a more fluent way:
protected Closeable increaseIndentLevel() {
indentLevel++;
return Close.by(this::decreaseIndentLevel);
}
Close.by() is my helper class that creates a Closeable that will decrease the indent level just like I do above; I can use it like this:
try (final Closeable indention = increaseIndentLevel()) {
serializeChildren()
}
Unfortunately OpenJDK javac 17 with linting turned on doesn't recognize my cleverness, and instead complains:
[WARNING]
auto-closeable resource indention is never referenced in body of corresponding try statement
I understand that try-with-resources requires that I declare some variable. I can't say try (increaseIndentLevel()) for example. (I also can guess the reason: the creators of this feature didn't generalize enough and instead created unnecessarily restrictive rules for the obvious, 99% use case. In reality there is no need conceptually to require a variable here; if the body needs to reference something, the compiler is smart enough to notice that the referenced variable is not present.)
Any idea how to get around this warning?
As a last resort, what identifier do I use with @SuppressWarnings() to make this warning go away in javac? (I had to supress the warning, because it turns such a pretty solution into something so ugly.)
I'd write something like this to avoid mutability. Without seeing more of your use case it's hard to know what to suggest: