从静态对象访问特定 class 实现

Access specific class implementation from static object

在 java 中是否可以在对特定静态对象调用方法时获得特定实现 class?

我想达到的目标:

    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";
        }
    }

好的,我设法通过用通用 class 替换枚举来解决这个问题。

解决方案:

    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";
        }
    }

如果可以改进,请在评论中告诉我