Way to specify multiple interfaces in Java

后端 未结 6 784
清酒与你
清酒与你 2020-12-29 10:04

I have two interfaces, HasClickHandlers and DoesFancyFeedback. Then I have some UI objects that implement both interfaces - for example, a B

相关标签:
6条回答
  • 2020-12-29 10:17

    You may try to use generics:

    public < T extends HashClickHandlers & DoesFancyFeedback > void foo (
            T aThingIPassedIn
        )
    {
        aThingIPassedIn.addClickHandler( );
        aThingIPassedIn.doFancyFeedback( );
    }
    
    0 讨论(0)
  • 2020-12-29 10:17

    Although that would be ugly, you could propably make it an Object and cast it. For the calling method, it would be the easiest way.

    0 讨论(0)
  • 2020-12-29 10:21

    No need for a third interface nor additional method.

    Optional.ofNullable((HasClickHandlers & DoesFancyFeedback)clickyFeedbackThing).ifPresent(then -> {
        then.addClickHandler();
        then.doFancyFeedback();
    });
    
    0 讨论(0)
  • 2020-12-29 10:37

    No, there is no such a thing in Java.

    You would have to use the option you mention of creating a third interface. That way you'll be explicitly declaring your intention to use a new type.

    Is not that verbose after all ( considering the alternative ), because you would just type:

    public interface FancyWithHandler 
           extends HashClickHandlers , DoesFancyFeedback {} 
    

    You don't need to include the methods. And then just use it:

    FancyWithHandler clickyFeedbackThing = aThingIPassedIn;
    clickyFeedbackThing.addClickHandler();
    clickyFeedbackThing.doFancyFeedback();     
    

    While the generic option looks interesting, probably at the end you'll end up creating a much more verbose thing.

    0 讨论(0)
  • 2020-12-29 10:39

    I do not think that there is a better way to do what you want. I just wanted to suggest you to do the following. You can create method (let's call it foo) that accepts argument that requires 2 interfaces:

    <T extends HasClickHandlers & DoesFancyFeedback> void foo(T arg);
    

    Please pay attention on one ampersand between 2 your interfaces.

    0 讨论(0)
  • 2020-12-29 10:41

    I wouldn't want a Button to implement any of those interfaces. What you're describing sounds more like the province of an event listener. Better to have the listener implement plain and fancy click handlers, and pass the listener into the Button or UI component. It's more of a delegation model that keeps processing out of the UI components and in separate classes that you can change at will.

    0 讨论(0)
提交回复
热议问题