Definition and Purpose
Marker Interface:
Type Definition:
Example:
public class MyClass implements Serializable { // Implementação }
Compile Time Check:
Example with Serializable:
ObjectOutputStream.writeObject(myObject); // Garante que myObject seja Serializable
Marking Accuracy:
Example:
public interface MyMarkerInterface extends MySpecificInterface { // Sem métodos adicionais }
Examples of Usage
Serializable:
Example:
public class Person implements Serializable { private String name; private int age; // Getters, setters, etc. }
Set Interface as Restricted Marker:
Marker Notes:
Example:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MyMarkerAnnotation { } @MyMarkerAnnotation public class MyClass { // Implementação }
When to use Marker Interface vs. Marker Annotation:
Use marker annotation if:
Advantages of Bullet Notes
Example:
@MyFrameworkAnnotation public class MyClass { // Implementação }
Usage Decision
To define a type:
Part of an annotation-based framework:
Use a bullet note.
Final Example
public interface MyTypeMarker { } public class MyClass implements MyTypeMarker { // Implementação } public void process(MyTypeMarker obj) { // Processa apenas objetos marcados com MyTypeMarker }
Bookmark Note:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MyAnnotationMarker { } @MyAnnotationMarker public class MyClass { // Implementação }
Summary
Complement
Marker interfaces:
The above is the detailed content of Item Use marker interfaces to define types. For more information, please follow other related articles on the PHP Chinese website!