[英]Java Store Specific Class Type in HashMap
I'm trying to implement a command line interface where you can search for products on a marketplace.我正在尝试实现一个命令行界面,您可以在其中搜索市场上的产品。
In order to allow for multiple marketplaces, I implemented a Marketplace interface.为了允许多个市场,我实现了一个市场接口。 I plan on having a hash map that maps a marketplace's name (ex. Amazon) to a class the implements the Marketplace interface.
我计划有一个哈希映射,将市场的名称(例如亚马逊)映射到实现 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");
}
}
How would I go about storing a class the implements the marketplace class inside a hash map as a value, and later getting that class from the hash map and call one of the static methods?我将如何将在哈希映射中实现市场类的类存储为值,然后从哈希映射中获取该类并调用其中一个静态方法?
I think you want something like this:我想你想要这样的东西:
Map<String, Class<? extends Marketplace>> descriptionsToClasses = new HashMap<>();
descriptionsToClasses.put("Amazon Marketplace", Amazon.class);
And finally, to invoke static methods:最后,调用静态方法:
Class<? extends Marketplace> marketplaceClass = descriptionsToClasses.get("Amazon Marketplace");
Method staticSearchMethod = marketplaceClass.getMethod("searchForProduct", String.class);
staticSearchMethod.invoke(null, "foo");
Make sure that the static method you are invoking is visible in the scope.确保您正在调用的静态方法在作用域中可见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.