javacavaj
javacavaj

Reputation: 2971

Generic Type Specification for Class Object

I'm using a HashMap and the method show below to track change listeners for class types. The IDE is giving a warning

[rawtypes] found raw type: java.lang.Class
  missing type parameters for generic class java.lang.Class<T>. 

What type for Class needs to be specified to resolve the warning?

private HashMap<Class, Set<ChangeListener>> classChangeListeners;

/**
 * Adds a ChangeListener to the listener list for the specified class type. The class type
 * specified must be a subclass of {@link BusinessObject}.
 *
 * @param  <T>  the type of BusinessObject.
 * @param  cls  the class type.
 * @param  listener  the ChangeListener to be added.
 */
public <T extends BusinessObject> void addChangeListener(Class<T> cls, ChangeListener listener)
{
 if (!classChangeListeners.containsKey(cls))
 {
  classChangeListeners.put(cls, new TreeSet<ChangeListener>());
 }

 classChangeListeners.get(cls).add(listener);
}

Upvotes: 4

Views: 3029

Answers (1)

Steven Schlansker
Steven Schlansker

Reputation: 38526

If you don't care to specify the type of the particular Classes you are working with, you can use Class<?> instead of the raw type Class.

In some cases you'd want to wildcard it, Class<? extends BusinessObject> or parametrize it, Class<T> - but usually Class<?> will be sufficient, and it's hard to infer what you actually want from a short snippet.

Also, it looks like you're using a Map containing Sets. You could look into using a Multimap which has this functionality built in and makes it a lot nicer to work with.

Upvotes: 5

Related Questions