Implementing Generic Interface in Java

后端 未结 7 1981
忘了有多久
忘了有多久 2020-12-24 12:38

I have a Java generics question I was hoping someone could answer. Consider the following code:

public interface Event{}
public class AddressChanged implemen         


        
相关标签:
7条回答
  • 2020-12-24 13:11

    An implementation like this won't work due to the constraints of the java specification. But if you're not afraid to use AOP or some sort of an IOC-Container you could use annotations for that. Than your Aspects or the container could manage the messaging infrastructure and call the methods you annotate.

    First you have to create the annotations.

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface EventConsumer {}
    
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Handles{}
    

    The you may annotate your class like that:

    @EventConsumer
    public class AddressHandler{
        @Handles
        public void handle(AddressChanged e){}
        @Handles
        public void handle(AddressDiscarded e){}
    }
    
    0 讨论(0)
提交回复
热议问题