在Java接口可选方法 [英] Optional method in Java Interface

查看:1163
本文介绍了在Java接口可选方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个方法定义的接口,我会的不可以想需要其中的一些。

I have an interface with several method definitions, and I would not like to require some of them.

这可能吗?如果是的话,我怎么能实现呢?

Is this possible? if so, how can i implement this?

我已经尝试设置 @optional 的注解,但是这似乎并没有工作。

I have tried setting an annotation of @Optional but this doesn't seem to work.

我一定在某处定义可选注释?

Do i have to define the Optional annotation somewhere?

推荐答案

虽然我同意其他的答案,应该注意的是在JDK中存在这样的可选方法。例如,<一个href="http://download.oracle.com/javase/6/docs/api/java/util/List.html#add%28int,%20E%29"><$c$c>List.add()是可选的。实现必须抛出UnsupportedOperationException如果他们不想要实现此方法。

Although I agree with the other answers, one should note that such optional methods exist in the JDK. For example, List.add() is optional. Implementations must throw an UnsupportedOperationException if they don't want to implement this method.

如果您希望能够知道是否可选方法的实施与否,那么你可以添加另一种方法(不可选):

If you want to be able to know if the optional method is implemented or not, then you could add another method (not optional) :

/**
 * Returns true if optionalOperation() is supported and implemented, false otherwise
 */
boolean isOptionalOperationSupported();

/**
 * implements he foobar operation. Optional. If not supported, this method must throw
 * UnsupportedOperationException, and isOptionalOperationSupported() must return false.
 */
void optionalOperation();

这篇关于在Java接口可选方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆