Jeff Verdegan wrote:That depends on what you're trying to do. If you want to define a type for a certain amount of compile-time type-safety for some purpose, then a marker interface can provide that, but an annotation can't. (Not that I can think of a particular case where one might need that, but that doesn't mean there isn't one.)
The only use of marker interfaces I've ever seen was
testing its presence on an object using the
instanceof operator. I'm not very skilled in annotations, but I assume it can be always done with them.
How to provide type safety using marker interface? Since it by definition does not contain any method, even if you declare a variable or parameter of that type, you won't be able to call any methods* on it without casting it first, which breaks the type safety. Let's say you create a method which requires a list that supports random access. You could ensure this by declaring the parameter as
RandomAccess, but it certainly smells bad. If
RandomAccess extended
List, it would be something different, but in this case it would not be a marker interface (as it would have inherited some methods). Though the idea is entertaining.
* You can call Object's methods on such variable, but you can do so on any object variable in Java, so this is moot.