Nothing entered.
This is about providing a flexible and convenient API to get values from dictionaries or maps which accept values of object type, or some other very generic type.
For instance, in JPPFJobMetadata we have:
private final Map<Object, Object> metadata = new HashMap<>();
@Override
public Object getParameter(final Object key) {
return metadata.get(key);
}
@Override
public Object getParameter(final Object key, final Object def) {
Object value = metadata.get(key);
return value != null ? value : def;
}
So, to get e.g. String values we'd have to perform a cast to String:
JobMetadata metadata = job.getSLA().getJobMetadata();
String value1 = (String) metadata.getParameter("my.key.1");
String value2 = (String) metadata.getParameter("my.key.2", "myDefaultValue2");
Now, if we rewrite the 2 methods above as follows:
@Override
public <T> T getParameter(final Object key) {
return (T) metadata.get(key);
}
@Override
public <T> T getParameter(final Object key, final T def) {
T value = (T) metadata.get(key);
return value != null ? value : def;
}
then we can get values without explicit cast, since the type can be inferred at compile time:
String value1 = metadata.getParameter("my.key.1");
String value2 = metadata.getParameter("my.key.2", "myDefaultValue2");
In some use cases, the type cannot be inferred at compile-time, for instance when the result of getParameter() with a single argument is provided as a method call argument. In such cases, there must be an explicit cast, so we're no worse than before:
public class MyObject {
public void myMethod(String arg) {
}
}
myObject.myMethod((String) metadata.getParameter("my.key.1"));
myObject.myMethod(metadata.getParameter("my.key.2", "myDefaultValue2"));
Note how, for the second invocation, we still don't need to cast explicitely, since the type can be inferred from the non-null default value.
For now, I see 3 APIs where this can be applied:
- JobMetadata and its implementation JPPFJobMetadata
- DataProvider and its implementation MemoryMapDataProvider
- the parameters map in JPPFTaskBundle
What we can do is implement a generic implementation in org.jppf.utils.collection and use it instead of the 3 existing implementations. As a bonus, this also means we'll have less code at the end of the day.
Really delete this comment?
Really delete this comment?
The issue was updated with the following change(s):