[英]Java Store Specific Class Type in HashMap
我正在尝试实现一个命令行界面,您可以在其中搜索市场上的产品。
为了允许多个市场,我实现了一个市场接口。 我计划有一个哈希映射,将市场的名称(例如亚马逊)映射到实现 Marketplace 接口的类。
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");
}
}
我将如何将在哈希映射中实现市场类的类存储为值,然后从哈希映射中获取该类并调用其中一个静态方法?
我想你想要这样的东西:
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");
确保您正在调用的静态方法在作用域中可见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.