📜 ⬆️ ⬇️

Practical use of multiple bounds generic in Java

I would not be much mistaken if I assume that very few people actively use this language feature. For those who do not remember what it is you can read here . I will pass to practice.


I came across a problem: it is necessary to send an already existing event (GWT) at the touch of a button, but to put an attribute (Command) before sending. It would seem, what have the patterns ...
But with what:


The method itself for creating a button is trivial, command is a class field:


Component createEventLink(String link, final Event<?> event) { TextButton button = new TextButton(link, new SelectHandler() { @Override public void onSelect(SelectEvent e) { //event.setCommand(command); bus.fire(event); } }); return new WidgetComponent(button); } 

Problem in line:


 //event.setCommand(command); 

The Event object has no such method. The solution seems to be obvious: inherit our events from the intermediate class CommandEvent, which will have this method and which inherits from Event. Our method now looks like this:


 Component createEventLink(String link, final CommandEvent<?> event) { TextButton button = new TextButton(link, new SelectHandler() { @Override public void onSelect(SelectEvent e) { event.setCommand(command); bus.fire(event); } }); return new WidgetComponent(button); } 

Eureka? Ha! Here we find that one of our events is already inherited from another child class (eg GwtEvent) and cannot inherit our CommandEvent class in any way.
The next step is to create the ICommandEvent interface with the setCommand () method and each of our events implements it. Our method now looks like this:


 Component createEventLink(String link, final Event event) { TextButton button = new TextButton(link, new SelectHandler() { @Override public void onSelect(SelectEvent e) { if (event instanceof ICommandEvent) { ((ICommandEvent) event).setCommand(command); } else { throw new IllegalStateException("Only ICommandEvent allowed"); } bus.fire(event); } }); return new WidgetComponent(button); } 

Well ugly! In addition, any event can be passed to it, and it will be detected only at launch, which is not good.


And then it's time to recall the topic of this note - multiple bounds generic in Java. With them, our method looks like this:


 <E extends Event<?> & ICommandEvent> Component createEventLink(String link, final E event) { TextButton button = new TextButton(link, new SelectHandler() { @Override public void onSelect(SelectEvent e) { event.setCommand(command); bus.fire(event); } }); return new WidgetComponent(button); } 

Exactly what was required.


')

Source: https://habr.com/ru/post/344054/


All Articles