MethodHandle.invokeExact() can match the performance of direct invocation, but it requires constant folding to do so. Otherwise results are similar to Java reflection(e.g [1]).
While TrustFinalNonStaticFields can be used, it’s a sledgehammer where a scalpel is really be more appropriate. The internal @Stable facility provides the desired semantics and precision, but it is heavily locked down, with privileged code checks and export restrictions. Could this be made more accessible (or perhaps a variant restricted to just final fields)? Informing the compiler that a final field is a true lazy initialized constant, with no store-to-final seems a pretty useful construct in general. I can understand that the long term desire is that this shouldn’t be necessary, and should be inferred [3], but at that point the annotation is still useful as documentation and legacy compatibility. If nothing else could it be allowed in non-privileged code via some flag? It seems odd that the much more aggressive facility (TrustFinalNonStaticFields) is simpler to use than a more targeted one. Thanks! [1] https://www.optaplanner.org/blog/2018/01/09/JavaReflectionButMuchFaster.html [2] http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/65464a307408/src/java.base/share/classes/jdk/internal/vm/annotation/Stable.java [3] https://bugs.openjdk.java.net/browse/JDK-8058164