Search code examples
javastatic-initialization

Is there a way in Java to detemine if a method is called in a static initializer (or not)?


as in a way to check appropriate use of a static registry:

class AClass {
     static final IDType = IDregistry.registerId(...);
}

class IDRegistry {
     public static registerId(...)
     {
          if(isCalledInStaticInitializer()) {
               return(new IDType(...));
          }
          assert false : "NO NO - can't do this !!!";
     }
}

Solution

  • I don't think you should do this. But if you insist, this would get you started:

    public static boolean isCalledInStaticInitializer()
    {
        for (StackTraceElement ste : Thread.currentThread().getStackTrace())
        {
            if("<clinit>".equals(ste.getMethodName()))
            {
                return true;
            }
        }
        return false;
    }
    

    Source: In section 2.9 of the JVM Specification ("Special Methods"):

    "A class or interface has at most one class or interface initialization method and is initialized (§5.5) by invoking that method. The initialization method of a class or interface has the special name <clinit>"