The compiler reports an error because you are trying to add to the map processors an entry with an incompatible type. At compile time the compiler does not know what the type of T is. Type T will be determined by the client which uses the method getOutputProcessors. Method processors.put expects that the first parameter is exactly the type of Class<T> (T will be determined only by code that uses the method getOutputProcessors), but you are always passing the same value of ClassA.class. The second parameter of the method processors.put is also incorrect, it should be exactly the type of Map<T, CellProcessor>, and you are passing permanently argument of type Map<ClassA, CellProcessor>. Treat type T as an independent type, so in the code of your method T is not equivalent to ClassA. The correct version of your method should look like this:
public static <T> Map<Class<T>, Map<T, CellProcessor>> getOutputProcessors(Class<T> key, Map<T, CellProcessor> classProcessors) {
Map<Class<T>, Map<T, CellProcessor>> processors = new HashMap<Class<T>, Map<T, CellProcessor>>();
processors.put(key, classProcessors);
return processors;
}
You can use this method in the following manner:
Map<Class<ClassA>, Map<ClassA, CellProcessor>> processorsA = getOutputProcessors(ClassA.class, classAProcessors);
Map<Class<ClassB>, Map<ClassB, CellProcessor>> processorsB = getOutputProcessors(ClassB.class, classBProcessors);
But in this way the map processorsA and processorsB are not compatible and you will not be able to merge them into one map. So you need to use different type of map than Map<Class<T>, Map<T, CellProcessor>>.
The best way is to create (or not if it already exists) a super type for ClassA and ClassB (for example a class or interface with name ClassBase). getOutputProcessors method that uses superclass ClassBase looks as follows:
public static Map<Class<? extends ClassBase>, Map<? extends ClassBase, CellProcessor>> getOutputProcessors() {
Map<Class<? extends ClassBase>, Map<? extends ClassBase, CellProcessor>> processors =
new HashMap<Class<? extends ClassBase>, Map<? extends ClassBase, CellProcessor>>();
processors.put(ClassA.class, getOutputCellProcessorsForClassA());
processors.put(ClassB.class, getOutputCellProcessorsForClassB());
return processors;
}
If for some reason you can not have in your code superclass ClassBase then you can use a method that looks as follows:
public static Map<Class<? extends Object>, Map<? extends Object, CellProcessor>> getOutputProcessors3() {
Map<Class<? extends Object>, Map<? extends Object, CellProcessor>> processors =
new HashMap<Class<? extends Object>, Map<? extends Object, CellProcessor>>();
processors.put(ClassA.class, getOutputCellProcessorsForClassA());
processors.put(ClassB.class, getOutputCellProcessorsForClassB());
return processors;
}
I hope my answer will help you
Tis not necessarilyClassA, but that's what you are trying to force.ClassA/ClassBare enums.