What is a marker interface, and how is it used at runtime?
A marker interface is an interface with no methods at all. It does not say what the class can do, it only says what kind of class it is.
public class Main {
public static void main(String[] args) {
Order o = new Order();
System.out.println(describe(o));
}
}
And here is the marker and the class that has it.
// A marker interface. There is nothing in it.
public interface Auditable {
}
public class Order implements Auditable {
private final String id;
public Order(String id) {
this.id = id;
}
}
And how is it used at runtime? You ask the object whether it has the marker, and then you do something extra for the ones that do.
public class Main {
public static void main(String[] args) {
Order o = new Order();
System.out.println(describe(o));
}
static String describe(Object item) {
if (item instanceof Auditable) {
// Write down what happened.
System.out.println("audit: " + item);
return "audited";
}
return "plain";
}
}
And that is the whole of it. The interface carries no behaviour. Its only job is to carry a label that the code can ask about.
the kind of interface what it has what it is for
-------------------------- -------------------- ------------------
a normal interface method signatures the behaviour
a marker interface nothing the type of the thing
And there is one detail worth knowing about, and it is why the marker was useful in the first place. Before generics, the only way to ask "is this object of a certain kind" was with the instanceof operator, and that only works with a class or an interface. So a marker interface was the only way to group the objects together without giving them any behaviour.
And there is a second detail worth knowing about. The marker is often checked with a helper method, so that the check is in one place and the message is the same everywhere.
public final class AuditLog {
private AuditLog() {
}
public static void record(Object item) {
if (item instanceof Auditable) {
System.out.println("audit: " + item);
}
}
}
So the rule to remember is this. A marker interface carries a label with no behaviour, and the code asks about the label with instanceof.
The last question in this topic is about why annotations took over.