Java generics pass parameters
•
Java
I hope someone can help me get rid of this trouble
I did this:
public static <T> void myMethod(Map<Class<T>,MyInterface<T>> map) { }
Use the parameter t to ensure that the class used as the key is the same as the class used as the parameter in myinterface
Now I want to pass a different mapping as a key, and of course the corresponding implementation of myinterface
But it doesn't work. Syntax errors are caused by type parameters This is the code. I hope it's self - explanatory
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"); } } }
Solution
You can't do this because there are no constraints defined in map's put () method between keys and values If you want to ensure that the map is populated correctly (that is, create such constraints), hide some maps behind APIs that will check for correctness, such as:
public <T> void registerInterface(Class<T> clazz,MyInterface<T> intf) { map.put(clazz,intf); }
Then, simply call registerinterface instead of filling the map manually
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码