Java 中是否存在用于满足接口的空方法的习语?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/884292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:13:51  来源:igfitidea点击:

Is there an idiom in Java for empty methods which exist to satisfy an interface?

javainterfaceannotationsoopidioms

提问by camdez

Let's say I have a class Fooimplementing an interface such as MouseListener. The MouseListenerinterface consists of five methods but I only wish to override one of them (mouseClicked()). Is there a standard, idiomatic way of formatting the other methods?

假设我有一个类Foo实现了一个接口,例如MouseListener. 该MouseListener接口由五个方法组成,但我只想覆盖其中一个 ( mouseClicked())。是否有一种标准的、惯用的方式来格式化其他方法?

My inclination was to write the following:

我的倾向是写以下内容:

@Override
public void mouseClicked(MouseEvent e) {
    // (...) <-- actual code here
}

@Override
public void mouseEntered(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mouseExited(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mousePressed(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mouseReleased(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

I'm a fan of making it explicit that methods are intentionally blank rather than accidentally left so, but I'm not crazy about all the vertical space given up for basically nothing. I've also seen the following format:

我很喜欢明确表示方法是故意空白而不是意外留下,但我并不为所有垂直空间基本上什么都没有而感到疯狂。我还看到了以下格式:

public void mouseClicked(MouseEvent e) {
    // (...) <-- actual code here
}

public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

I'm generally OK with this and I understand the author's intent, but it gets really ugly when the (recommended) @Overrideannotations are added.

我通常对此没有意见,我理解作者的意图,但是当添加(推荐的@Override注释时,它变得非常难看。

I'm not a particularly experienced Java coder so I figured I'd ask if there was a convention. Thoughts?

我不是一个特别有经验的 Java 编码员,所以我想我会问是否有约定。想法?

回答by Jan Gressmann

I do it the same way you do, if theres nothing there leave at one line. Maybe put a comment on top of a large block of 'implementation one-liners'.

我和你做的一样,如果没有任何东西留在一行。也许在一大块“实现单行”的顶部发表评论。

回答by Dónal

In this particular case you should follow wilums2's advice and extend MouseAdapter instead of implementing MouseListener. The purpose of these adapter classes is so that you don't have to provide empty implementations when you're only implementing some of the methods of an interface.

在这种特殊情况下,您应该遵循 wilums2 的建议并扩展 MouseAdapter 而不是实现 MouseListener。这些适配器类的目的是,当您只实现接口的某些方法时,您不必提供空的实现。

More generally, the short answer is 'no', there is no standard convention for how to document empty methods, though I generally use something like

更一般地说,简短的回答是“不”,没有关于如何记录空方法的标准约定,尽管我通常使用类似的东西

@Override
void foo() {
  // No implementation necessary
}

回答by user101884

Use MouseAdapter

使用鼠标适配器

回答by Scott Stanchfield

In general, what you're talking about is an extension of the Null Object Pattern. You're definining a Null Object and extending it by only overriding the methods you care about.

一般来说,你所说的是空对象模式的扩展。您正在定义一个空对象并通过仅覆盖您关心的方法来扩展它。

As an example of a way to automate this, in my JavaDude Bean Annotations (http://code.google.com/p/javadude/wiki/Annotations), you can do something like the following. [NOTE: I wouldn't recommend doing this for MouseListener, as the MouseAdapter already exists and you can just subclass it... The following is useful for other large interfaces where you only want to implement a few select methods]

作为自动化此方法的示例,在我的 JavaDude Bean 注释 ( http://code.google.com/p/javadude/wiki/Annotations) 中,您可以执行以下操作。[注意:我不建议为 MouseListener 执行此操作,因为 MouseAdapter 已经存在,您可以将其子类化...以下对于您只想实现几个选择方法的其他大型接口很有用]

@Bean(nullObjectImplementations = @NullObject(type=MouseListener.class))
public class MyMouseHandler extends MyMouseHandlerGen {
    public void mouseClicked(MouseEvent e) {
        // your handling of a MouseClick
    }
}

You can then use MyMouseHandler to handle the click.=

然后您可以使用 MyMouseHandler 来处理点击。=

Note: MouseAdapter was a reallybad choice for the name of the class in the JRE/JDK. It's not an instance of the GoF Adapter pattern; it's really a Null Object implementation of a MouseListener.

注意:MouseAdapter对于 JRE/JDK 中的类名来说是一个非常糟糕的选择。它不是 GoF Adapter 模式的实例;它实际上是一个 MouseListener 的 Null Object 实现。

BTW: You can put @Override on the same line as the method declaration - for your example you can have

顺便说一句:您可以将@Override 与方法声明放在同一行 - 对于您的示例,您可以

@Override public void mousePressed(MouseEvent e) { /* not needed */ }
// et al

回答by Yaroslav Mytkalyk

There are several ways to do this. The Oracle java conventionsp6.4 (page 11) says the empty methods should look like

有几种方法可以做到这一点。在甲骨文Java约定P6.4(第11页)说,空的方法应该看起来像

public void empty() {}

There is also a document by Steve Yohananwritten in 2003 ant it says

还有一个Steve Yohanan在 2003 年写的文档ant 它说

public void empty()
{
}

Though I haven't found any convention for "empty method as interface stub". So as a conclusion, there is no standardized way of doing this. Some prefer leaving a comment, some prefer making it single line, some write it as any other method with blank body.

虽然我还没有找到任何“空方法作为接口存根”的约定。因此,作为结论,没有标准化的方法可以做到这一点。有些人更喜欢留下评论,有些人更喜欢单行,有些人像其他任何方法一样写成空白正文。

回答by Carl Manaster

MouseAdapter is great for this specific case and the Adapter idiom is great in general. An Adapter has empty implementations of all the methods of the interface, allowing you to subclass and implement only those methods that are relevant to your class. The Adapter could alternatively, as Andrew Hare suggests, throw NotImplementedException's.

MouseAdapter 非常适合这种特定情况,而 Adapter 惯用语通常也很棒。适配器具有接口的所有方法的空实现,允许您子类化并仅实现与您的类相关的那些方法。或者,正如 Andrew Hare 所建议的,适配器可以抛出 NotImplementedException。

回答by Steve Kuo

The purpose of a listener is to be notified of some events. If the listener interface contains more method callbacks than you need, then just ignore the ones you don't care about. In your case MouseAdapterwas designed for this exact purpose. Do notthrow UnsupportedOperationExceptionas the caller is most likely not expecting the exception. It also most likely violates the listener interface's contract as each method is expected to be implemented.

侦听器的目的是通知某些事件。如果侦听器接口包含比您需要的更多的方法回调,那么只需忽略您不关心的那些。在您的情况下,MouseAdapter正是为此目的而设计的。千万不能UnsupportedOperationException作为主叫方很可能不是预期的异常。它也很可能违反了侦听器接口的契约,因为每个方法都应该被实现。

回答by Rob

I guess I'd describe it as "no-op implementations" or perhaps use the term "adapter". As others have noted, Java provides a MouseAdapterclass which does what you want. Strictly speaking, it doesn't quite fall into the definition of the Adapter pattern, which transforms one API into another, but frankly, I tend to be pragmatic about naming such things.

我想我会将它描述为“无操作实现”,或者使用术语“适配器”。正如其他人所指出的,Java 提供了一个MouseAdapter可以执行您想要的操作的类。严格来说,它并不完全属于适配器模式的定义,它将一种 API 转换为另一种 API,但坦率地说,我倾向于务实地命名这些东西。

Probably the most important thing to do is be clear that you intend for the method to have no implementation. In the specific case of the MouseAdapter, you probably don't want to go around throwing UnsupportedOperationException, but in general, it's probably a good signal that you don't intend to provide an implementation. A comment in the source code (or better, the method documentation) to explain just why you're not implementing the interface fully is usually necessary.

可能最重要的事情是明确您打算让该方法没有实现。在 的特定情况下MouseAdapter,您可能不想四处投掷UnsupportedOperationException,但总的来说,这可能是一个很好的信号,表明您不打算提供实现。通常需要在源代码(或更好的方法文档)中添加注释来解释您没有完全实现接口的原因。

回答by Tom Hawtin - tackline

I don't think it particularly matters. For my personal tastes I don't like to see the closing brace next to the opening, which gives:

我认为这不是特别重要。就我个人的喜好而言,我不喜欢在开头旁边看到右括号,它给出了:

public void mouseEntered(MouseEvent e) {
}

A bit empty, but okay. In the case of a return value we can make it look consistent, wich you don't get with the []style.

有点空,但还好。在返回值的情况下,我们可以使其看起来一致,而您不会使用[]样式。

But when it comes to the rare case in loops, I like a semicolon in there:

但是当谈到循环中的罕见情况时,我喜欢在那里加一个分号:

// Made up example.
while (++i < len && str.charAt(i) != '
public void mouseEntered(MouseEvent e) {
    ;
}
') { ; }

Which would give:

这会给:

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount) {
    return;         
} 

In the case of catchclauses, you'd better have a good excuse in a comment (perhaps dropping an interrupt).

catch子句的情况下,你最好在评论中有一个很好的借口(也许打断一下)。

回答by Geeks On Hugs

I found this while searching for this exact question. I'm using on scroll where I need onScrollStateChanged but not onScroll. I was leaning towards:

我在搜索这个确切的问题时发现了这个。我在需要 onScrollStateChanged 但不需要 onScroll 的地方使用滚动。我倾向于:

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount) {return;}

However, I like the second example you give (with braces on same line). It's compact and clean and can consistently express the idea that it is intentionally left blank.

但是,我喜欢你给出的第二个例子(在同一行有大括号)。它紧凑而干净,可以始终如一地表达有意留空的想法。

Edit: this is what I settled on:

编辑:这是我决定的:

##代码##

This one has a lot of parameters so it doesn't look as nice as on one line but you get the idea.

这个有很多参数,所以它看起来不像一行那么好,但你明白了。