[Marker Interface](https://ja.wikipedia.org/wiki/%E3%83%9E%E3%83%BC%E3%82%AB%E3%83%BC%E3%82%A4%E3% 83% B3% E3% 82% BF% E3% 83% 95% E3% 82% A7% E3% 83% BC% E3% 82% B9) is a class that does not include a method definition and simply implements the interface. Is to show that has a particular attribute.
An example is the `` `Serializableinterface (Chapter 12). Implementing this interface shows that instances of that class are writable to
ObjectOutputStream```.
With the advent of marker annotations (Item39), the marker interface may seem obsolete, but it's a mistake.
The marker interface has two advantages over marker annotations.
The first is that ** the marker interface defines the type, but not the marker annotation **. This makes it possible to catch errors at compile time that cannot be caught by marker annotations until run time.
Java's serialization feature uses the `Serializable``` marker interface to indicate that the type is serializable. The ```ObjectOutputStream.writeObject``` method serializes the passed object, but requires its arguments to be serializable. If the argument of this method is
Serializable``` (actually it takes an Object), it can be detected by compilation when an argument of improper type comes. The second is that the ** marker interface is more concise and targeted **. When the target of the marker annotation is ```ElementType.TYPE```, all classes and interfaces are targeted, but in the case of the marker interface, it is limited to the class that implements it. ```set```The interface is such a limiting marker interface. Set is implemented only in Collection subtypes, but does not add anything to the methods defined in Collection. Set redefines some of the methods in the Collection, so it is not generally considered a marker interface. However, it is easy to imagine a marker interface that applies only to a particular interface subtype and does not redefine the interface's methods. Such a marker interface describes an immutable value (?) For the entire object, or indicates that its instance is adapted to be processed by a method of another particular class (in this sense,
. The `` Serializableinterface indicates that the instance is suitable for being processed by
ObjectOutputStream```).
** The advantage of marker annotation is that it is part of a larger annotation feature. ** Therefore, marker annotations are considered for consistency in the annotation-based framework.
First, the only way to add markers to elements other than classes and interfaces is to use marker annotations. Regarding markers for classes and interfaces *** Have you ever written one or more methods for only this marked object? *** *** Consider. If you have something to write, you should use the marker interface. This allows method argument type checking to be done at compile time. If you don't write it, you should use marker annotations. Marker annotations should be chosen for marking in frameworks that use a lot of annotations.
Recommended Posts