2014-10-01 37 views
0

我想通過反射創建類映射。如何告訴java反射,我只需要一些接口的實現?指定界面的反射貼圖

我需要的是這樣的:

public interface Interface {} 
public class InterfaceImpl1 implements Interface {} 
public class InterfaceImpl2 implements Interface {} 
public class Main { 
    private static Map<Class<Interface>, String> classMap = new HashMap(); 
    static { 
     classMap.put(InterfaceImpl1.class, "impl1"); // <- Compiler says it's an error 
     classMap.put(InterfaceImpl2.class, "impl2"); // <- Also an error :(
    } 
} 

我要某種類型和多態的增加反射。它應該如何?

回答

1

使用通配符,表明你想要的任何Interface亞型。

private static Map<Class<? extends Interface>, String> classMap = new HashMap<>(); 
+0

謝謝你救了我的很多時間:) – smt 2014-10-01 05:52:05