I know that its not possible to use generics with Enums but im searching for a way to implement a method for a enum with different return types.
For example I have following enum:
enum TestEnum {
TEST_INTEGER() {
@Override
public Integer getValue() {
return 123;
}
},
TEST_STRING() {
@Override
public String getValue() {
return "Test";
}
};
public abstract Object getValue();
}
In this case TEST_INTEGER
and TEST_STRING
are implementations of TestEnum
. Thats why the method getValue()
has the return type Object
and not Integer
or String
when the getValue()
is invoked. That means in each case I have to cast to the concerning Classtype.
Is there any better way to get diretly the different Classtypes?
Yes, java allows to "reduce" the return type (see here).
But in your context, this does not make sense conceptually!
Think of
TestEnum someEnum = ...
Integer val = someEnum.getValue();
How is the compiler supposed to know which one of your enum constants you actually assigned to that value?
Therefore the compiler could only understand:
Integer val = TestEnum.TEST_INTEGER.getValue();
But well, what if you just know that it is some instance of TestEnum you are dealing with?!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments