import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
assertEquals("getFieldNames length", 2, names.size());
assertArrayEquals(fFieldNames, names.toArray(new String[names.size()]));
}
+
+ // ------------------------------------------------------------------------
+ // getFieldValue
+ // ------------------------------------------------------------------------
+
+ @Test
+ public void testGetFieldValueExists() {
+ String value = fRootField.getFieldValue(String.class, fFieldName1);
+ assertNotNull(value);
+ assertEquals(fValue1, value);
+ }
+
+ @Test
+ public void testGetFieldValueExistsButWrongType() {
+ Integer value = fRootField.getFieldValue(Integer.class, fFieldName1);
+ assertNull(value);
+ }
+
+ @Test
+ public void testGetFieldValueDoesntExist() {
+ String value = fRootField.getFieldValue(String.class, "no-field");
+ assertNull(value);
+ }
+
+ @Test
+ public void testGetFieldValueNullValue() {
+ ITmfEventField subField = new TmfEventField("subField", null, null);
+ ITmfEventField rootField = new TmfEventField("rootField", null,
+ new ITmfEventField[] { subField });
+
+ String value = rootField.getFieldValue(String.class, "subField");
+ assertNull(value);
+ }
+
+ @Test
+ public void testGetFieldValueAssignableValue() {
+ /*
+ * fValue2 is an Integer, but the method should allow us to use it as a
+ * Number for example.
+ */
+ Number value = fRootField.getFieldValue(Number.class, fFieldName2);
+ assertNotNull(value);
+ assertEquals(fValue2, value);
+ }
}
import java.util.Collection;
import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
/**
* The generic event payload in TMF. Each field can be either a terminal or
*/
ITmfEventField getField(String @NonNull ... path);
+ /**
+ * Retrieve the value of a field, given an expected name/path and a value
+ * type.
+ *
+ * This is a utility method that will do the proper null and instanceof
+ * checks on the returned values of {@link #getField} and {@link #getValue}
+ * accordingly.
+ *
+ * @param type
+ * The expected type of this field, to which the returned value
+ * will then be cast to.
+ * @param fieldName
+ * The name or path of the subfield to look for
+ * @return The value if a field with this name exists and the value is of
+ * the correct type, or 'null' otherwise
+ * @since 2.1
+ */
+ default <T> @Nullable T getFieldValue(@NonNull Class<T> type, @NonNull String @NonNull ... fieldName) {
+ ITmfEventField field = getField(fieldName);
+ if (field == null) {
+ return null;
+ }
+ Object value = field.getValue();
+ if (value == null || !type.isAssignableFrom(value.getClass())) {
+ return null;
+ }
+ @SuppressWarnings("unchecked")
+ T ret = (T) value;
+ return ret;
+ }
+
}