How to explicitly call a static initializer in Java?

So, as an example, I have this JNI code:

/** This literally does nothing. It purpose is to call the static initializer early to detect if we have issues before loading. */ public static void nothing() { } static { // should be loaded by CLib if (CLib.hasGNUTLS() == 1) { globalinit(); } } 

I found that I was literally creating a β€œnothing” function to call it earlier if necessary, but I also want it to be called if it was referenced earlier or if we don't call nothing() . Now I could make some kind of unpleasant logic, including checking Boolean, but then you get into thread safety and blah. I suppose you could, but it's ugly. Is there a way to explicitly call GNUTLS.<clinit>(); ?

+4
source share
1 answer

The static initializer always starts before your method, because the initializer starts when the class is initialized. JLS-8.7. Static initializers (partially)

A static initializer declared in a class is executed when the class is initialized ( Β§12.4.2 ). Together with any field initializers for class variables ( Β§8.3.2 ), static initializers can be used to initialize class class variables.

And you cannot explicitly call any initializer ( static or otherwise). However, Class.forName(String) says (partially)

Calling forName("X") initializes the class named X

+2
source

All Articles