Search code examples
javainterfacesemantics

In what context are statements in Java interface definitions executed?


I'm looking at the definition of org.apache.maven.plugin.Mojo:

public interface Mojo
{
    String ROLE = Mojo.class.getName();
    [...]
}

I'm lost. To my knowledge, Java interfaces are a set of method signatures. So what's this line which looks like a statement doing here? What are the semantics? For example:

  • When does that line get "executed"?
  • In the context in which that line runs, what does Mojo refer to? What is its type?
  • In the context in which that line runs, what does Mojo.class refer to? I assume its type is java.lang.Class?
  • In what context can I read that ROLE variable? What is the syntax for doing so? What will the variable contain?
  • Can I write to that ROLE variable?

Solution

  • All the fields of an interface are implicitely public, static and final. So this is the same as writing

    public static final String ROLE = Mojo.class.getName();
    

    It defines a constant, that all the users of the interface can use, as any other constant: Mojo.ROLE. This line is executed when the Mojo interface is initialized by the ClassLoader. Mojo.class is the Mojo class, indeed of type java.lang.Class<Mojo>. Since the package of the class is org.apache.maven.plugin, the value of the constant will be "org.apache.maven.plugin.Mojo".

    Look here for the relevant section of the Java language specification.