I need to put test values in a class, somehow like in this simplified example:
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class TestVal {
private static Map<Class<?>, Object> dummyValues = Maps.newHashMap();
static {
dummyValues.put(String.class, "Banana");
dummyValues.put(Integer.class, 42);
}
@SuppressWarnings("unchecked")
static final <T> T ofType(Class<T> type) {
return (T) dummyValues.get(type);
}
public static void main(String[] args) {
List<? extends Object> list =
Lists.newArrayList(ofType(String.class), ofType(Integer.class));
for (Object object : list) {
System.out.printf("%s: %s%n", object, object.getClass().getName());
}
}
}
which, once run, gives me:
Banana: java.lang.String
42: java.lang.Integer
so it’s fine as a “basic” system.
I’d like more type-safety though.
I was trying to study Guava’s ImmutableClassToInstanceMap but… I find it a little difficult, take a look at this method signature:
public static
<B, S extends B>
ImmutableClassToInstanceMap<B>
copyOf(
Map<? extends Class<? extends S>,
? extends S> map
)
brutal, isn’t it? How would I use it for “any” type? Did not see an example on Google’s Wiki..
Can I move “one step up” without “going all the way” like the thing above? Am I missing another obvious way to do the same?
Eh? All you need to do with
ImmutableClassToInstanceMapis something likeand then you just call
map.getInstance(String.class)to get out aString.The generics on
copyOf()are complicated but necessary, but for this case you’ll almost certainly want to just use the builder instead.