属性、数组、列表、映射和索引器

使用属性引用进行导航很容易。为此,请使用句点表示嵌套属性值。Inventor类的实例pupintesla,是使用示例中使用的类部分列出的数据进行填充的。要沿着对象图导航并获取特斯拉的出生年份和普平的出生城市,我们使用以下表达式:

  • Java

  • Kotlin

// 计算为1856
int year = (Integer) parser.parseExpression("birthdate.year + 1900").getValue(context);

String city = (String) parser.parseExpression("placeOfBirth.city").getValue(context);
// 计算为1856
val year = parser.parseExpression("birthdate.year + 1900").getValue(context) as Int

val city = parser.parseExpression("placeOfBirth.city").getValue(context) as String

属性名称的首字母不区分大小写。因此,上面示例中的表达式可以写为Birthdate.Year + 1900PlaceOfBirth.City。此外,属性可以选择通过方法调用访问,例如,getPlaceOfBirth().getCity()而不是placeOfBirth.city

通过使用方括号表示法获取数组和列表的内容,如下例所示:

  • Java

  • Kotlin

ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();

// 发明家数组

// 计算为"感应电动机"
String invention = parser.parseExpression("inventions[3]").getValue(
		context, tesla, String.class);

// 成员列表

// 计算为"尼古拉·特斯拉"
String name = parser.parseExpression("members[0].name").getValue(
		context, ieee, String.class);

// 列表和数组导航
// 计算为"无线通信"
String invention = parser.parseExpression("members[0].inventions[6]").getValue(
		context, ieee, String.class);
val parser = SpelExpressionParser()
val context = SimpleEvaluationContext.forReadOnlyDataBinding().build()

// 发明家数组

// 计算为"感应电动机"
val invention = parser.parseExpression("inventions[3]").getValue(
		context, tesla, String::class.java)

// 成员列表

// 计算为"尼古拉·特斯拉"
val name = parser.parseExpression("members[0].name").getValue(
		context, ieee, String::class.java)

// 列表和数组导航
// 计算为"无线通信"
val invention = parser.parseExpression("members[0].inventions[6]").getValue(
		context, ieee, String::class.java)

通过在括号内指定文字键值来获取映射的内容。在以下示例中,因为officers映射的键是字符串,我们可以指定字符串文字:

  • Java

  • Kotlin

// 官员字典

Inventor pupin = parser.parseExpression("officers['president']").getValue(
		societyContext, Inventor.class);

// 计算为"伊德沃尔"
String city = parser.parseExpression("officers['president'].placeOfBirth.city").getValue(
		societyContext, String.class);

// 设置值
parser.parseExpression("officers['advisors'][0].placeOfBirth.country").setValue(
		societyContext, "克罗地亚");
// 官员字典

val pupin = parser.parseExpression("officers['president']").getValue(
		societyContext, Inventor::class.java)

// 计算为"伊德沃尔"
val city = parser.parseExpression("officers['president'].placeOfBirth.city").getValue(
		societyContext, String::class.java)

// 设置值
parser.parseExpression("officers['advisors'][0].placeOfBirth.country").setValue(
		societyContext, "克罗地亚")