Skip to content

Commit 59862e4

Browse files
committed
Add convenience value builder
1 parent 6556acf commit 59862e4

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

api/all/src/main/java/io/opentelemetry/api/common/Value.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,11 @@ static Value<List<KeyValue>> of(Map<String, Value<?>> value) {
8484
return KeyValueList.createFromMap(value);
8585
}
8686

87+
/** Returns a new {@link ValueBuilder} instance for creating an arbitrary {@link Value}. */
88+
static ValueBuilder builder() {
89+
return new ValueBuilderImpl();
90+
}
91+
8792
/** Returns the type of this {@link Value}. Useful for building switch statements. */
8893
ValueType getType();
8994

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* Copyright The OpenTelemetry Authors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package io.opentelemetry.api.common;
7+
8+
public interface ValueBuilder {
9+
10+
default ValueBuilder put(String key, String value) {
11+
put(key, Value.of(value));
12+
return this;
13+
}
14+
15+
default ValueBuilder put(String key, long value) {
16+
put(key, Value.of(value));
17+
return this;
18+
}
19+
20+
default ValueBuilder put(String key, double value) {
21+
put(key, Value.of(value));
22+
return this;
23+
}
24+
25+
default ValueBuilder put(String key, boolean value) {
26+
put(key, Value.of(value));
27+
return this;
28+
}
29+
30+
ValueBuilder put(String key, Value<?> value);
31+
32+
Value<?> build();
33+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
* Copyright The OpenTelemetry Authors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package io.opentelemetry.api.common;
7+
8+
import java.util.ArrayList;
9+
import java.util.List;
10+
11+
class ValueBuilderImpl implements ValueBuilder {
12+
13+
private final List<KeyValue> keyValues = new ArrayList<>();
14+
15+
@Override
16+
public ValueBuilder put(String key, Value<?> value) {
17+
keyValues.add(KeyValue.of(key, value));
18+
return this;
19+
}
20+
21+
@Override
22+
public Value<?> build() {
23+
return Value.of(keyValues.toArray(new KeyValue[0]));
24+
}
25+
}

0 commit comments

Comments
 (0)