Java: static final String population in static block results in NoClassDefFoundError

302 views Asked by At

I have this class:

public final class Validator {

    private static final String TEST_VALUE = "test";
    private static final String TEST;

    static {
        TEST = TEST_VALUE + "_test";
    }

    private Validator() {}

    public static void validate() {
        //Do something with TEST
    }
}

When I call Validator.validate() from somewhere else, I get an java.lang.NoClassDefFoundError: Could not initialize ....Validator

As I understand from Static block in Java not executed, final static Strings are prepopulated at compile-time.

Is this the case if the variable is only defined in the static block? I would expect that the compiler would not try to pre-populate that final variable.

If it's not the case... What could be the error?

With a debugger I noticed that the static block is never executed, but I don't get why...

This is Java 8 btw.

UPDATE:

The problem was a java error in the static block. The strange thing is that there were no errors in the logs pointing to anything of the static block and the debugger did not halt at the static constructor, so I thought that the problem lied somewhere else.

1

There are 1 answers

4
davidxxx On BEST ANSWER
static {
    TEST = TEST_VALUE + "_test";
}

is probably not your real code since it should not cause any runtime exception.
You rise ajava.lang.NoClassDefFoundError because probably you encounter an exception in the static bloc :

static {
        TEST = TEST_VALUE + "_test";
      }

which prevents the class to be loaded.

You should check that you log suitably any exception which could occur at least in the standard output of the program.