我正在尝试实现一个命令行界面,您可以在其中搜索市场上的产品。
为了允许多个市场,我实现了一个市场接口(interface)。我计划有一个 HashMap ,将市场名称(例如 Amazon)映射到实现 Marketplace 接口(interface)的类。
public interface Marketplace {
static ArrayList<Product> searchForProduct(String productName) {
throw new IllegalStateException("searchForProduct hasn't been defined");
};
static ArrayList<Listing> getListings(Product product) {
throw new IllegalStateException("getListings hasn't been defined");
}
}
我将如何将实现市场类的类存储在 HashMap 中作为值,然后从 HashMap 中获取该类并调用其中一个静态方法?
最佳答案
我想你想要这样的东西:
Map<String, Class<? extends Marketplace>> descriptionsToClasses = new HashMap<>();
descriptionsToClasses.put("Amazon Marketplace", Amazon.class);
最后,调用静态方法:
Class<? extends Marketplace> marketplaceClass = descriptionsToClasses.get("Amazon Marketplace");
Method staticSearchMethod = marketplaceClass.getMethod("searchForProduct", String.class);
staticSearchMethod.invoke(null, "foo");
确保您调用的静态方法在作用域中可见。
关于Java 在 HashMap 中存储特定的类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60480266/