开发者

Generic Interface design using marker annotations on enums

Can I use a marker annotation on an enum when designing a generic interface?

Or, is it possible to type check annotation references at compile time?

I am developing a set of interfaces to process messages, each message will consist of a message type and the message content. I'd like to code the message types as enums and then define the other interfaces based on this. Something like this,

public interface MessageHandler<E extends Enum<E>> {

    boolean handles( E messageType );
}

I don't want any enum to be used here, I can add a Marker Interface MessageType like so,

public interface MessageHandler<E extends Enum&开发者_高级运维lt;E> & MessageType> {

    boolean handles( E messageType );
}

I understand that Marker Annotations are preferable to Marker Interfaces these days, but I see no way to use them here. Is it possible or do I just stick with the interface?


Annotations are abused like XML was. Why "marker annotation" if an interface perfectly expresses the type?

In your case, there is no need for handler to require an enum type. Why does it care? You may indeed have all message types as enums, however that is none of super handler interface's business. Every sub handler has intimate knowledge of the types it's handling, it can handle enum and whatnot.

enum TypeX implements MessageType 
{ 
   X1, 
   X2 
}

class HandlerX extends Handler<TypeX>
    handle(TypeX type)
        if(type==X1) 
        ...

----

class TypeY implements MessageType
{ 
   int x; 
}

class HandlerY extends Handler<TypeY>
     handle(TypeY type)
         if(type.x==0) 
         ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜