Is it possible in java to get a specific implementation class while calling a method on a specific static object?
The thing i want to achive:
public static void main(String[] args) {
String testBase = TestEnum.TEST_BASE.getFields().TEST_STATICS_BASE_FIELD;
String testExtension = TestEnum.TEST_EXTENSION.getFields().TEST_STATICS_EXTENSION_FIELD; //this doesn't compile
}
public enum TestEnum {
TEST_BASE(new TestStaticsBase()),
TEST_EXTENSION(new TestStaticsExtension()),
;
public TestStaticsBase fields;
TestEnum(TestStaticsBase fields) {
this.fields = fields;
}
public TestStaticsBase getFields() {
return fields;
}
public static class TestStaticsBase {
public final String TEST_STATICS_BASE_FIELD = "TEST_STATICS_BASE_FIELD";
}
public static class TestStaticsExtension extends TestStaticsBase {
public final String TEST_STATICS_EXTENSION_FIELD = "TEST_STATICS_EXTENSION_FIELD";
}
}
CodePudding user response:
Ok, i managed to resolve this problem by replacing enum with a generic class.
Solution:
public static void main(String[] args) {
String testBase = TestEnum.TEST_BASE.getFields().TEST_STATICS_BASE_FIELD;
String testExtension = TestEnum.TEST_EXTENSION.getFields().TEST_STATICS_EXTENSION_FIELD; //this doesn't compile
}
public static class TestEnum<T extends TestEnum.TestStaticsBase> {
public static final TestEnum<TestEnum.TestStaticsBase> TEST_BASE = new TestEnum<>(new TestStaticsBase());
public static final TestEnum<TestStaticsExtension> TEST_EXTENSION = new TestEnum<>(new TestStaticsExtension());
;
public T fields;
public TestEnum(T fields) {
this.fields = fields;
}
public T getFields() {
return fields;
}
public static class TestStaticsBase {
public static final String TEST_STATICS_BASE_FIELD = "TEST_STATICS_BASE_FIELD";
}
public static class TestStaticsExtension extends TestStaticsBase {
public static final String TEST_STATICS_EXTENSION_FIELD = "TEST_STATICS_EXTENSION_FIELD";
}
}
If this can be improved please let me know in comments
