希望有人可以帮助我摆脱这种困扰.
我做了这个方法:
public static <T> void myMethod(Map<Class<T>,MyInterface<T>> map) { }@H_403_5@使用参数T以确保用作键的类与用作MyInterface中的参数的类相同.
现在我想传递一个不同类作为键的映射,当然还有MyInterface的相应实现.
但它不起作用,因类型参数而导致语法错误.这是代码,我希望是自我解释.
import java.util.HashMap; import java.util.Map; public class Test { public static void main(String[] args) { Map<Class<?>,MyInterface<?>> map = new HashMap<Class<?>,MyInterface<?>>(); // Map<Class<Object>,MyInterface<Object>> map = new HashMap<Class<Object>,MyInterface<Object>>(); map.put(Object.class,new MyObjectImpl()); //if I use Map<Class<Object>,MyInterface<Object>> I get a compiler error here //because map<String> is not map<Object> basically map.put(String.class,new MyStringImpl()); //this would be possible using <?>,which is exactly what I don't want // map.put(String.class,new MyIntegerImpl()); //<?> generates anyways a compiler error myMethod(map); } //use T to make sure the class used as key is the same as the class of the parameter "object" in doSomething public static <T> void myMethod(Map<Class<T>,MyInterface<T>> map) { } interface MyInterface<T> { void doSomething(T object); } static class MyObjectImpl implements MyInterface<Object> { @Override public void doSomething(Object object) { System.out.println("MyObjectImpl doSomething"); } } static class MyStringImpl implements MyInterface<String> { @Override public void doSomething(String object) { System.out.println("MyStringImpl doSomething"); } } static class MyIntegerImpl implements MyInterface<Integer> { @Override public void doSomething(Integer object) { System.out.println("MyIntegerImpl doSomething"); } } }@H_403_5@