Reputation: 1294
I am creating a library, which includes a function having argument as enum
public class Service
{
public static void setServiceMode(SERVICE_MODE mode)
{
}
}
Now, I have a project which is importing the above library, and calling the "setServiceMode" function as follows
Service.setServiceMode(SERVICE_MODE.LOGIN)
My problem is that where to declare the enum (SERVICE_MODE), as I have to pass it in library function argument, and values to enum are project specific. I don't want to make changes in my library. How to achieve this in java ?
Upvotes: 0
Views: 106
Reputation: 200148
The recommendation is to use interfaces where you need extensible enums. Here is an outline of the setup giving you the proper type constraints. In your library, define
interface ServiceMode<E extends Enum<E> & ServiceMode<E>> {}
and declare your posted method as
public static <E extends Enum<E> & ServiceMode<E>> void setServiceMode(E mode) {}
In your client code, define an enum:
enum MyServiceMode implements ServiceMode<MyServiceMode> {}
The type bound on ServiceMode
guarantees that it can only be parameterized by an enum which implements it and the additional constraint on the type passed to setServiceMode
guarantees that it is a subtype of ServiceMode
parameterized by itself.
Upvotes: 1
Reputation: 65813
You could make the library just accept any enum
if that's acceptable:
public class Service {
public static <E extends Enum<E>> void setServiceMode(E mode) {
}
// Or a pre-generics version.
public static void setServiceMode2(Enum mode) {
}
}
public enum SERVICE_MODE {
LOGIN,
LOGOUT;
}
public void test() {
Service.setServiceMode(SERVICE_MODE.LOGIN);
Service.setServiceMode2(SERVICE_MODE.LOGIN);
}
Upvotes: 2
Reputation: 10342
Your Service class won't compile unless the SERVICE_MODE enum is in the classpath. Due to this strong dependency, the best idea is adding that enum to your library. If you cannot do this, then create a new library, which will be a dependency of yours.
Upvotes: 0
Reputation: 16605
SERVICE_MODE
will need to be contained in a library shared by both applications
Upvotes: 1