在Java接口可选方法可选、接口、方法、Java

2023-09-05 11:03:56 作者:海是倒过来的天

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

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中存在这样的可选方法。例如,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();
 
精彩推荐
图片推荐