binnyb binnyb - 6 months ago 13
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

@Optional
but this doesn't seem to work.

Do i have to define the
Optional
annotation somewhere?

Answer

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();