Introduce computeAttribute() in AttributeAccessor
This commit introduces computeAttribute() as an interface default method in the AttributeAccessor API. This serves as a convenience analogous to the computeIfAbsent() method in java.util.Map. Closes gh-26281
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -19,6 +19,7 @@ package org.springframework.test.context.support;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
@@ -200,6 +201,17 @@ public class DefaultTestContext implements TestContext {
|
||||
return this.attributes.get(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T computeAttribute(String name, Function<String, T> computeFunction) {
|
||||
Assert.notNull(name, "Name must not be null");
|
||||
Assert.notNull(computeFunction, "Compute function must not be null");
|
||||
Object value = this.attributes.computeIfAbsent(name, computeFunction);
|
||||
Assert.state(value != null,
|
||||
() -> String.format("Compute function must not return null for attribute named '%s'", name));
|
||||
return (T) value;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public Object removeAttribute(String name) {
|
||||
|
||||
Reference in New Issue
Block a user