Reputation: 36403
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:
Mojo
refer to? What is its type?Mojo.class
refer to? I assume its type is java.lang.Class
?ROLE
variable? What is the syntax for doing so? What will the variable contain?ROLE
variable?Upvotes: 2
Views: 71
Reputation: 8386
- When does that line get "executed"?
Any member of an Interface
is static
and final
by default, so String ROLE
(which can effectivly be seen as
public static final String ROLE
will be initialized, as every static member, when the ClassLoader loads the class (by the first time, the class is referenced).
JLS - Loading of Classes and Interfaces
- 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?
Mojo is of the type java.lang.Class<Mojo>
- In what context can I read that ROLE variable? What is the syntax for doing so? What will the variable contain?
As it is implicit public static final
you can access it from everywhere by using Mojo.ROLE
or through the implementing classes by ClassName.ROLE
. As Class#getName() says in the java doc, it will contain the full qualified name of the object:
org.apache.maven.plugin.Mojo
- Can I write to that ROLE variable?
No, you cannot, because it is implicit final
Upvotes: 0
Reputation: 691735
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.
Upvotes: 3
Reputation: 3050
All fields in an interface are implicitly static and final. That answers some of your questions:
Mojo
refers to the interface itself, statically. It is a type itself, so it has no type.Mojo.class
refers to the java.lang.Class
of Mojo.ROLE
variable in any class that implements Mojo
. You can only read it statically, like Mojo.ROLE
.Upvotes: 0
Reputation: 8652
the variable get defined when class loader loads the class. interface variables are static final and can be accessed statically by any class that implements the interface.
public class MyClass implements Mojo{
.
.
.
}
access:
public void someMethod(){
System.out.println(MyClass.ROLE)
}
Upvotes: 0