SpEL reflection and static method invocation¶
SpEL (Spring Expression Language) supports reflection-based operations, allowing developers to access Java classes, invoke static methods, and instantiate objects directly within expression strings^[600-developer-spring-spring-spel.md]. This capability is primarily facilitated using the T() operator.
The T() Operator¶
The T() operator is used to specify a Java class within a SpEL expression^[600-developer-spring-spring-spel.md]. It returns a reference to the java.lang.Class instance for the given type.
Syntax¶
T(<fully_qualified_java_class>)
For example, to reference the String class, the expression is:
T(java.lang.String)
Static Method Invocation¶
Once a class is referenced via T(), static methods can be called directly on the returned class object^[600-developer-spring-spring-spel.md].
For example, the following expression calls a hypothetical static method valueOf:
T(java.lang.String).valueOf('data')
Practical Implementation¶
Reflection and static invocation are commonly handled programmatically using SpelExpressionParser and StandardEvaluationContext^[600-developer-spring-spring-spel.md].
Code Example¶
The following Java code demonstrates how to parse a SpEL expression that uses the T() operator to access a class type programmatically^[600-developer-spring-spring-spel.md]:
public static Object spel(String content){
ExpressionParser parser = new SpelExpressionParser();
// TEMPLATE_EXPRESSION allows parsing of #{ ... } delimiters
Expression exp = parser.parseExpression(content, ParserContext.TEMPLATE_EXPRESSION);
EvaluationContext context = new StandardEvaluationContext();
return exp.getValue(context);
}
When the input string #{T(java.lang.String)} is passed to this method, the result is the Class object itself^[600-developer-spring-spring-spel.md].
Instantiation¶
In addition to static methods, SpEL can use class references to invoke constructors and create new instances ("new Bean")^[600-developer-spring-spring-spel.md]. This is achieved by calling new on the class reference provided by T().
Sources¶
^[600-developer-spring-spring-spel.md]
Related¶
- [[Spring-SpEL]]
- [[Java Reflection]]