我的目标是在容器类中反映所有静态类,并将它们收集到的映射中simpleName -> class
。
可以毫无问题地“手工”完成,但是我真的很想通过编程来完成。
例如,给定:
public interface MyInterface {
void doThing();
}
还有一个包含几个实现该接口的类的类
public class MyStuff {
public static class One implements MyInterface {...}
public static class Two implements MyInterface {...}
public static class Three implements MyInterface {...}
}
以下手动创建的地图可以正常运行。
public void demo(String jsonString) {
Map<String, Class<? extends MyInterface>> myMap = ImmutableMap.of(
"One", One.class,
"Two", Two.class,
"Three", Three.class,
)
}
我可以将其用于Gson反序列化等有用的事情:
MyInterface object = new Gson().fromJson(jsonString, myMap.get("One"))
现在,我想要做的是不是构建地图的手,而是使用反射来构建它。
理想的情况是:
Map<String, Class<? extends MyInterface>> options = new HashMap<>();
for (Class<?> cls : MyStuff.class.getDeclaredClasses()) {
options.put(cls.getSimpleName(), cls)
}
但这不能编译,如getDeclaredClasses
固定的Class<?>
。
有趣的是,Java似乎具有运行时所需的所有信息。我可以打印出每个类,看看它是的正确实现类MyInterface
。我觉得我应该能够得到我需要的类型。但是,我不知道如何进行最后的编译时跃点来获得Class<? extends MyInterface>
这在Java中可行吗?
如果需要嵌套类实现MyInterface
,则应进行检查,一旦完成,就可以安全地强制转换值。
private static Map<String, Class<? extends MyInterface>> buildOptions() {
Map<String, Class<? extends MyInterface>> options = new HashMap<>();
for (Class<?> cls : MyStuff.class.getDeclaredClasses()) {
if (MyInterface.class.isAssignableFrom(cls)) {
options.put(cls.getSimpleName(), cls.asSubclass(MyInterface.class));
}
}
return Collections.unmodifiableMap(options); // Make it immutable
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句