Is it possible to design your own Java Type, similar to an extensible enum
?
For instance, I have user roles that a certain module uses and then a sub-package provides additional roles.
What would be involved on the JDK side of things?
Is it possible to design your own Java Type, similar to an extensible enum
?
For instance, I have user roles that a certain module uses and then a sub-package provides additional roles.
What would be involved on the JDK side of things?
Since Enums can't be extended, you have to fake it.
Make a class with a protected constructor.
Then you can create public static final FakeEnum
instances in your class.
public class FakeEnum {
private String name;
private Object something;
protected FakeEnum(String name, Object otherParam) {
this.name = name;
this.something = otherParam;
}
// public getters
public static final FakeEnum ONE = new FakeEnum("one", null);
public static final FakeEnum TWO = new FakeEnum("two", null);
public static final FakeEnum THRE = new FakeEnum("thre", null);
}
And then you can extend it and add some more things to it like so:
public class ExtendedFakeEnum extends FakeEnum {
public static final FakeEnum EXTENDED_ONE = new FakeEnum("extended_one", null);
public static final FakeEnum EXTENDED_TWO = new FakeEnum("extended_two", null);
}
The concept of an extensible enum doesn't make sense. An enum is used to declare statically the entire set of instances that will ever be made for its own type. Allowing it to be extended would make that impossible to ensure.
Designing your own type in Java is impossible. Anything you need to do can be done using various design patterns.
Ok,
What I will do is write an interface and then several implementations for how to find users to notify in a particular event. The correct implementation will get injected at run-time and then it will do whatever it needs to do to find the correct users. That implementation may simply take arguments to configure the group name to look for and then return a list of users.
I am learning to use interfaces / design by contract more. Most of my development in the past has only ever had a single implementation so I saw this as a moot point and forgot about that tool / means.
Thanks,
Walter
If you need an "extensible enum" it might be that a dictionary would suit you better, look at java.util.Dictionary<K,V>
where K is the keyname (how you would refer to the particular value, and V is the value/object that should be returned by said Key.
I think thats the closest I've ever come to an extensible Enum.
Also, have a look at this question on SO, this might solve it too.