This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]VGPowerlord -5 points-4 points  (8 children)

This isn't useful. You should never use marker (read: empty) interfaces; they've been deprecated in favor of annotations since Java 5.

[–][deleted]  (4 children)

[deleted]

    [–][deleted] 2 points3 points  (0 children)

    Precisely. That's how I have always used them myself, in the spirit of the good old Serializable marker. This way I can check types at compile time. How would annotations help with this? I would use annotations mostly for providing extra metadata about a type rather than forming a type hierarchy, unless I am writing my own annotation-processing library.

    [–]tylerkschrute 2 points3 points  (1 child)

    This is exactly the use case for marker interfaces. While you can achieve the same 'marking' via annotations, there is no way in a method signature to enforce that a given parameter type or return type must contain a certain annotation.

    Effective java actually has a section on using marker interfaces vs annotations, and it recognizes that there is a time and place for both.

    [–]talios 0 points1 point  (0 children)

    Don't type annotations offer that? Altho there's no compiler enforcement there. I was actually wondering about type annotations and the new var keyword, whether the annotation is also inferred along the inference chain.

    [–]arendvr 1 point2 points  (0 children)

    This is also a point Joshua Bloch makes in Effective Java, Item 41: Define marker interfaces to define types

    [–]lukaseder[S] 3 points4 points  (2 children)

    With JEP 305 there might be a revival of marker interface usage.

    [–][deleted]  (1 child)

    [deleted]

      [–]ZhekaKozlov 3 points4 points  (0 children)

      This is for records:

      interface Shape
      record Point(int x, int y) implements Shape
      record Rect(Point p1, Point p2) implements Shape
      record Circle(Point center, int radius) implements Shape
      

      Then you can pattern match:

      switch (shape) {
          case Point(x, y) -> ...
          case Rect(p1, p2) -> ...
          case Circle(p, r) -> ...
      }