I want a method argument to define the class a HashMap will accept. Something along the lines of:
private HashMap hashMap = new HashMap();
public boolean createMap(Object obj) {
return hashMap = new HashMap<String, obj.getClass()>() != null;
}
You can't do what you're trying to do: you can't "define the class a HashMap will accept" because at runtime a HashMap will accept all classes.
What you could do, on the other hand, is:
private Map<String, ?> map;
public <V> void createMap(Class<V> clazz) {
map = Collections.checkedMap(new HashMap<String, V>(),
String.class, clazz);
}
...which will actually enforce the restrictions you're trying to create, with reflection. In this case, your hashMap member should have type Map<String, Object>, though it will enforce
public <V>? What is T used for in that example?<V>.define a typed function that accepts the type you desire as value for the map
public <T> Map<String, T> checkedStringKeyMap(Class<T> type) {
return Collections.checkedMap(new HashMap<String, T>(), String.class, type);
}
then create your map as follows
Map<String, Person> persons = checkedStringKeyMap(Person.class);
public boolean <T> createMap() { return hashMap = new HashMap<String, T>() != null; }? Did you try your example? What is the error you receive?true