Pergunta

When I generate a class in clojure (through gen-class), I get the following definition upon inspection via javap:

public class foo.bar extends java.lang.Object implements java.io.Serializable{
    public final java.lang.Object state;
    public static {};
    public foo.bar();
    ...
}

I wonder what the construct public static {} means as I never saw something like this before …

Can someone please enlighten me?

Foi útil?

Solução

The static section contains code which runs during static class initialization (before any instances of the class are created).

Think of having namespace-level code with side effects in Clojure -- those side effects take place as soon as anyone requires or uses the namespace, even if they don't actually call any functions. This is a comparable situation.

Outras dicas

If you take a look at full output of javap (with javap -c ...) you'll see that it's just a bunch of code that clojure compiler put to be executed ahead of first class access. Usually it is interning of vars which are used later and so on.

sounds like a static initialization block on the class.

You can use that block to initialize all static variables of the class. However, I had never seen the "public" qualifier before it.

Try this in Java so you see the order of invocation

public class StaticTest {

  { 
    System.out.println("Anonymous Block.");
  }

  static {
    //probably equivalent to that public {} you see on your code.
    System.out.println("Static Block.");
  }

  public StaticTest() {
     System.out.println("Constructor.");
  }

  public static void main(String[] args) {

    StaticTest test = new StaticTest() {
            {
                System.out.println("Anonymous block in instance.");
            }
    };
  }
}

when you execute this it prints the following:

> $ java StaticTest 
> Static Block. 
> Anonymous Block. 
> Constructor.
> Anonymous block in instance.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top