我有这个类称为Container:
public class Container {
private final Map<String, Object> map = new HashMap<>();
public void put(String name, Object value) {
map.put(name, value);
}
public Container with(String name, Object value) {
put(name, value);
return this;
}
public Object get(String name) {
return map.get(name);
}
public <R> R get(String name, Function<Object, R> mapper) {
Object value = get(name);
if (null == value) {
return null;
}
return mapper
.apply(value);
}
public <R> R get(String name, Class<R> type) {
Object value = get(name);
if (null == value) {
return null;
}
if (type.isAssignableFrom(value.getClass())) {
return type
.cast(value);
}
throw new ClassCastException(String
.format("%s -> %s", value.getClass(), type));
}
}
和类称为Token:
public class Token {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Token withValue(String value) {
setValue(value);
return this;
}
}
最后是班级的测试Token班
public class TokenTest {
@Test
public void verifyToken() {
verify("bar", new Token()
.withValue("bar"));
}
@Test
public void verifyContainer() {
Container tokens = new Container()
.with("foo", "bar")
.with("baz", "bat");
verify("bar", tokens.get("foo", String.class));
verify("bat", tokens.get("baz", String::valueOf)); // line 21
}
private void verify(String expected, String actual) {
verify(expected, new Token()
.withValue(actual));
}
private void verify(String expected, Token actual) {
Assert
.assertEquals(expected, actual.getValue());
}
}
繁星淼淼
qq_笑_17
相关分类