Reputation: 5248
I basically want to have an enum
with specific methods, e.g.
public interface PropertyTypeMethods {
public int getTypeId();
public void setTypeId(Integer typeId);
}
and something like
public enum BasePropertyTypes implements PropertyTypeMethods {
ONE, TWO;
private int typeId;
@Override
public int getTypeId() {
return typeId;
}
@Override
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
}
as well as an extended version of this enum, e.g.
public enum ExtendedPropertyTypes implements PropertyTypeMethods {
HUNDRED, THOUSEND;
// same as above
}
which would result in ONE.setTypeId(1)
==> ONE.getTypeId()==1 //true
. That is the basic concept. But now I want to call a generic method like e.g.
private <E extends Enum<E> & PropertyTypeMethods> void initEnum(Enum<E> curType) {
// the below approach does not work :-/
curType.setTypeId(1); // or any other reasonable value....
But somehow I cannot figure out what the correct method signature would be. Following this question I figured at least some part of the puzzle -
but still don't get it for the method signature. Still it remains unclear how to specify curType
properly in the signature to execute an appropriate call.
Upvotes: 1
Views: 917
Reputation: 2613
This will work :
private <E extends Enum<E> & PropertyTypeMethods> void initEnum(E curType) {
curType.setTypeId(1);
}
However, I don't think it's a good idea to make mutable Enum
s (they're meant to be labels over constant values, not state-carrying singletons). Furthermore, you shouldn' write methods that require an Enum
parameter when all they should care about is its interface :
// This will be easier to work with down the road
private void initEnum(PropertyTypeMethods curType) {
curType.setTypeId(1);
}
Upvotes: 2
Reputation: 443
The correct signature would simply be
private void initEnum(PropertyTypeMethods onject) {
object.setTypeId(1);
}
But as Andy Turner mentioned, enums are expected to be immutable, i.e. only final immutable field. Therefore, enums also have a constructor Enum Types.
If you have more complex enums, it is a common way to implement them as follows
public enum BasePropertyTypes implements PropertyTypeMethods {
ONE (new PropertyTypeMethods() {
@Override
public int getTypeId() {
return 1;
}
});
private final PropertyTypeMethods m;
BasePropertyTypes(PropertyTypeMethods m) {
this.m = m;
}
@Override
public int getTypeId()
{
return this.m.getTypeId();
}
}
But from your example, I would suggest to review your actual issue. Propably enums are not the proper way at all.
Upvotes: 1