binnyb binnyb - 2 years ago 117
Java Question

Optional method in Java Interface

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?

I have tried setting an annotation of

but this doesn't seem to work.

Do i have to define the
annotation somewhere?

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download