【问题标题】:How do I reference a nested type in SpEL?如何在 SpEL 中引用嵌套类型?
【发布时间】:2026-02-09 09:15:01
【问题描述】:

给定一个包含枚举的类:

public class MyClass {
    public enum NestedEnum {        
        value1(1),
        value2(2);

        private int code;

        private NestedEnum(int code) {
            this.code = code;
        }

        public int getCode() {
            return code;
        }
    }
}

如何引用 NestedEnum?这个:

#{T(MyClass.NestedEnum).value1.getCode()}

导致异常:

org.springframework.expression.spel.SpelEvaluationException: EL1005E:(pos 0): Type cannot be found 'namespace.MyClass.NestedEnum'

这个:

#{T(T(MyClass).NestedEnum).value1.getCode()}

导致异常:

org.springframework.expression.spel.SpelParseException: EL1043E:(pos 3): Unexpected token.  Expected 'rparen())' but was 'lparen(()'

我想不出任何其他好的选择。

【问题讨论】:

    标签: spring spring-el


    【解决方案1】:

    您必须使用$ 符号分隔枚举:

    #{T(MyClass$NestedEnum).value1.getCode()}
    

    【讨论】:

    • 在您的答案中指定Type->NestedEnum 更改会更好吗?问题中的“错误”代码通常应该被单独留下,以便答案中的修复更加明显。
    • 这也是一个解决方案,但我认为它会损害答案的可理解性。我也假设,这是提问者的复制和粘贴错误。Neverteheless,谢谢你的提示。