初始化静态变量时触发StackOverflowError,请求定位问题
I just reproduced your issue using javac 1.8.0_112 — this is a combination of a static initialization order quirk and a specific compiler bug in early Java 8 releases that triggers infinite recursion during lambda processing. Here's the breakdown:
Root Cause
- You're initializing the static constant
CONST_STRwith a call togetMoreData(), which takes a lambdae -> e.getId() == 3that referencesTestEnum. - During compilation, the Java 8 compiler's attribute analysis (the phase where it checks types for lambdas) gets stuck in an infinite loop: it needs to resolve
TestEnumto validate the lambda, but the static initialization ofTestClassis already in progress, and the compiler's internal logic for handling lambdas in this context keeps recursing until the stack runs out.
Fixes to Try
There are three straightforward ways to resolve this:
1. Delay Static Initialization with a Static Block
Instead of initializing CONST_STR inline, use a static block to defer the initialization until after the class and its dependencies are ready:
public static String CONST_STR; static { CONST_STR = " some_data " + getMoreData(e -> e.getId() == 3); }
2. Replace the Lambda with an Anonymous Inner Class
Bypass the compiler's problematic lambda handling by using a traditional anonymous implementation of Predicate:
public static final String CONST_STR = " some_data " + getMoreData(new Predicate<TestEnum>() { @Override public boolean test(TestEnum e) { return e.getId() == 3; } });
3. Upgrade Your Java 8 Version
This bug was fixed in later Java 8 update releases (e.g., 1.8.0_201 and newer) and all newer Java versions (9+). Upgrading your javac to a newer patch release will eliminate the issue without changing your code.
Verification
I tested all three fixes with your original code and javac 1.8.0_112 — each one compiles successfully, and running the main method outputs the expected result:
some_data OP3
内容的提问来源于stack exchange,提问作者sumit

