Java had support for something very like this, but no one used it, and they recently removed it. https://openjdk.org/jeps/486
It's too bad, it would be useful in this situation